[ACCEPTED]-Why should I implement ICloneable in c#?-icloneable

Accepted answer
Score: 121

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

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

Score: 29

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

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

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

Score: 19

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

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

Score: 9

Matt is correct, don't use it. Create your 4 own Copy() method (or similar name) and make it 3 perfectly clear in your public API whether your method 2 is creating a deep or shallow copy of your 1 object.

More Related questions