#141 – Implementing ICloneable for a Custom Type
November 5, 2010 4 Comments
A type can choose to implement the ICloneable interface, which includes the single Clone method. The intent of the Clone method is to create a copy of the object.
The simplest way to create a copy of the object is to call the Object.MemberwiseClone method.
public class Person : ICloneable { public string LastName { get; set; } public string FirstName { get; set; } public Person(string lastname, string firstname) { LastName = lastname; FirstName = firstname; } public object Clone() { return this.MemberwiseClone(); } }
If your intention is to make a deep copy and your type contains only members that are value types, this is sufficient. However, if the type contains members that are reference types, you’ll have to do more in order to get a deep copy.