#143 – An Example of Implementing ICloneable for Deep Copies
November 7, 2010 10 Comments
Here’s an example of implementing ICloneable in two custom classes so that you can use the Clone method to do a deep copy.
To do a deep copy of the Person class, we need to copy its members that are value types and then create a new instance of Address by calling its Clone method.
public class Person : ICloneable { public string LastName { get; set; } public string FirstName { get; set; } public Address PersonAddress { get; set; } public object Clone() { Person newPerson = (Person)this.MemberwiseClone(); newPerson.PersonAddress = (Address)this.PersonAddress.Clone(); return newPerson; } }
The Address class uses MemberwiseClone to make a copy of itself.
public class Address : ICloneable { public int HouseNumber { get; set; } public string StreetName { get; set; } public object Clone() { return this.MemberwiseClone(); } }
Cloning a Person:
Person herClone = (Person)emilyBronte.Clone();