Why should I implement ICloneable in c#?

Can you explain to me why I should inherit from ICloneable and implement the Clone() method?

If I want to do a deep copy, can't I just implement my method? Let's say MyClone()?

Why should I inherit from ICloneable? What are the advantages? Is it just a matter of making code "more readable"?


Solution 1:

You shouldn't. Microsoft recommends against implementing ICloneable because there's no clear indication from the interface whether your Clone method performs a "deep" or "shallow" clone.

See this blog post from Brad Abrams back in 2003(!) for more information.

Solution 2:

The ICloneable interface by itself isn't very useful, which is to say that there really aren't many situations where it's useful to know that an object is cloneable without knowing anything else about it. This is a very different situation from e.g. IEnumerable or IDisposable; there are many situations where it's useful to accept an IEnumerable without knowing anything other than how to enumerate it.

On the other hand, ICloneable may be useful when applied as a generic constraint along with other constraints. For example, a base class might usefully support a number of derivatives, some of which could be usefully cloned, and some of which could not. If the base type itself exposed a public cloning interface, then any derivative type which could not be cloned would violate the Liskov Substitution Principle. The way to avoid this problem is to have the base type support cloning using a Protected method, and allow derived types to implement a public cloning interface as they see fit.

Once that was accomplished, a method which wants to accept an object of a WonderfulBase type, and needs to be able to clone it, could be coded to accept a WonderfulBase object which supports cloning (using a generic type parameter with base-type and ICloneable constraints). Although the ICloneable interface would not itself indicate deep or shallow cloning, the documentation for WonderfulBase would indicate whether cloneable WonderfulBase should be deep- or shallow-cloned. Essentially, the ICloneable interface wouldn't accomplish anything that wouldn't be accomplished by defining ICloneableWonderfulBase, except that it would avoid having to define different names for every different cloneable base class.

Solution 3:

ICloneable is one of those artifacts in the BCL which has been controversial. There is no real reason IMHO to implement it. With that said if I am going to create a clone method then I do implement ICloneable, and I provide my own strong typed version of Clone.

The issue with ICloneable is it never indicated if Clone was a shallow or a deep copy which are very different things. The fact that there is no ICloneable<T> might be an indication on Microsoft's thoughts about ICloneable