Raghav55
Raghav55

Reputation: 3135

shallow and deep cloning in C# .net

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();

    }
}
  1. 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?

Upvotes: 0

Views: 1000

Answers (4)

crypted
crypted

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

Lasse V. Karlsen
Lasse V. Karlsen

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

Lazarus
Lazarus

Reputation: 43094

That's provided by the base Object class. Check the documentation here.

Upvotes: 0

Hans Kesting
Hans Kesting

Reputation: 39329

Every object inherits from "Object", even if you didn't specify. So it's there.

Upvotes: 1

Related Questions