C# Language ICloneable

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any C# Language Question?