Main

January 31, 2004

Copy Constructors, MemberwiseClone, and the ICloneable Interface

After looking at the options a bit, here are some conclusions about Copy Constructors, MemberwiseClone, and the ICloneable Inerface in C#:

1.       Generally favor factory methods (like Clone and Deserialize) over copy constructors unless you’re really aiming at value semantics. They’ll be more consistent with the way serialization works and the existing patterns.

2.       It’s easy to implement a Clone method in terms of a copy constructor and impossible to do the opposite, but…

3.       Object.MemberwiseClone supports writing Clone methods and not copy constructors.

4.       Like many things in the pre-generics flavor of C#, the “object” return type of ICloneable.Clone is unfortunate, but just deal with it.

5.       Don’t overlook using serialization if you just need some kind of copy operation.