class CloneExample : ICloneable
{
private int m_data ;
private double m_data2 ;
public object Clone()
{
return this.MemberwiseClone();
}
public CloneExample()
{
}
public CloneExample(int data1, int data2)
{
m_data = data1;
m_data2 = data2;
}
public override string ToString()
{
return String.Format("[d1,d2] {0} {1}", m_data, m_data2);
}
}
class Program
{
static void Main(string[] args)
{
CloneExample aEx = new CloneExample(10,20);
CloneExample aEx2 = (CloneExample)aEx.Clone();
Console.WriteLine("the first object value is {0}", aEx.ToString());
Console.WriteLine("the first object value is {0}", aEx2.ToString());
Console.Read();
}
}
- I wrote a exmaple to understand how shallow cloning works.In the above example in the
clone method I am calling this.MemberWiseClone() , since in the class I have not implemented the memeberwiseclone . who will provide the default implementation?
Memberwiseclone first create instance probably using Activator.CreateInstance which then iterates over all the fields within the type and set the value to the corresponding member/field.
But I would rather not use ICloneable at all. If I needed to use Cloning I use BinaryFormatter to serialize an object graph then deserialize it so that I would get new deeply cloned instance.