The ICloneable interface enables you to provide a customized implementation that creates a copy of an existing object.
Definition:
public interface ICloneable
{
// Summary:
// Creates a new object that is a copy of the current instance.
//
// Returns:
// A new object that is a copy of this instance.
object Clone();
}
Example:
public class Customer : ICloneable{
public string Name { get; set; }
public Address CustomerAddress { get; set; }
public object Clone()
{
Customer newCustomer = (Customer)this.MemberwiseClone();
newCustomer.CustomerAddress = (Address)this.CustomerAddress.Clone();
return newCustomer;
}
}
public class Address : ICloneable
{
public string StreetName { get; set; }
public int StreetNumber { get; set; }
public object Clone()
{
return this.MemberwiseClone();
}
}
Customer c1 = new Customer();
c1.Name = "c1";
Address a1 = new Address();
a1.StreetName = "Street1";
a1.StreetNumber = 1;
c1.CustomerAddress = a1;
Customer custClone = (Customer)c1.Clone();
custClone.Name = "c2";