Reputation: 3135
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();
}
}
Upvotes: 0
Views: 1000
Reputation: 10306
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.
Upvotes: 5
Reputation: 391496
The default implementation of MemberwiseClone
comes from the Object class in .NET.
The MemberwiseClone method uses reflection to do the job.
Upvotes: 1
Reputation: 43094
That's provided by the base Object class. Check the documentation here.
Upvotes: 0
Reputation: 39329
Every object inherits from "Object", even if you didn't specify. So it's there.
Upvotes: 1