Implementing ICloneable
I was doing a little work on the Design Guidelines
document tonight and I noticed this section that we added recently.
I thought I'd post it here for your comments. Where are you
using ICloneable today? Do you agree with this suggestion?
1.1 Implementing
ICloneable
The ICloneable interface contains a single Clone method, which is
used to create a copy of the current object.
public interface ICloneable
{
object
Clone();
}
?
Do not implement
ICloneable
There are two general ways to implement ICloneable, either as a deep, or
non-deep copy. Deep-copy copies the cloned object and all objects referenced by
the object, recursively until all objects in the graph are copied. A non-deep
copy (referred to as ‘shallow’ if only the top level references are copied) may
do none, or part of a deep copy.
Because the interface
contract does not specify the type of clone performed, different classes have
different implementations. A consumer cannot rely on ICloneable to let
them know whether an object is deep-cloned or not.
Note : If you need a cloning
mechanism, define your own Clone, or Copy methodology, and ensure that you
document clearly whether it is a deep or shallow copy. An appropriate pattern
is:
public
<type> Copy();
?
Do not use
ICloneable in public APIs