#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.
But.. string is not a value type!!!
Right, string isn’t a value type. But it IS immutable. And a new string is created whenever you assign to a string property/field. Which means that if you create a clone of an object that contains strings and then change those strings in one object, you won’t see the changes in the second object. So, for purposes of MemberwiseClone, you can treat the strings as value types.
Pingback: #828 – Implementing Both a Copy Constructor and ICloneable | 2,000 Things You Should Know About C#
Pingback: #829 – Add Comments to Indicate Shallow vs. Deep Copying | 2,000 Things You Should Know About C#