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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| 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.
1
2
3
4
5
6
7
8
9
10
| public class Address : ICloneable{ public int HouseNumber { get; set; } public string StreetName { get; set; } public object Clone() { return this.MemberwiseClone(); }} |
Cloning a Person:
1
| Person herClone = (Person)emilyBronte.Clone(); |

