Stats

51 Contributors: 2 Tuesday, December 13, 2016
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

ICloneable

Syntax

  • object ICloneable.Clone() { return Clone(); } // Private implementation of interface method which uses our custom public Clone() function.
  • public Foo Clone() { return new Foo(this); } // Public clone method should utilize the copy constructor logic.

Remarks

The CLR requires a method definition object Clone() which is not type safe. It is common practice to override this behavior and define a type safe method that returns a copy of the containing class.

It is up to the author to decide if cloning means only shallow copy, or deep copy. For immutable structures containing references it is recommended to do a deep copy. For classes being references themselves it is probably fine to implement a shallow copy.

NOTE: In C# an interface method can be implemented privately with the syntax shown above.

Related Examples