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 Apple class, we need to copy its members that are value types and then create a new instance of Color by calling its Clone method.
public class Apple : ICloneable { public double Size { get; set; } public ColorCustom Color { get; set; } public object Clone() { Apple newApple = (Apple)this.MemberwiseClone(); newApple.Color = (ColorCustom)this.Color.Clone(); return newPerson; } }
The Colorclass uses MemberwiseClone to make a copy of itself.
public class Apple : ICloneable { public int size { get; set; } public string color { get; set; } public object Clone() { return this.MemberwiseClone(); } }
Cloning an Apple:
Apple appleClone = (Apple)apple.Clone();