Search code examples
c#.netprogramming-languages

Why doesn't C#/.Net use the clone paradigm?


I was struck by how copying a collection object in C# can be quite cumbersome, especially if you want a deep copy. Is there a good design reason why .Net didn't go the Java clone() route, and is there some equivalent paradigm I've missed in C#/.Net?


Solution

  • Shallow Copies

    For shallow copies, .NET offers Object.MemberwiseClone.

    Deep Copies

    For deep copies, Microsoft suggests to implement a custom Copy method. Deep copies require intricate knowledge about the class itself -- in fact, for a given class, it might even make sense to make multiple different types of deep copy. Thus, there is no pre-defined method or interface for this purpose.

    But what about the ICloneable interface?

    There is the ICloneable interface, whose purpose might correspond roughly to Java's Object.clone. However, Microsoft advises against its use, since it does not specify how shallow or deep the copy needs to be for the interface to be implemented correctly.