Why should I implement ICloneable in c#?

Viewed 49575

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"?

4 Answers

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.

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

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

Related