0

I have created a class

 class MyClass:ICloneable
{
    public int val;
    public List<int> list;
    public MyClass()
    {
        list = new List<int>();
    }
    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

and I run the below class

class ProgramTest
{
    static void Main(string[] args)
    {
        MyClass objectA = new MyClass();
        objectA.list.Add(1);
        MyClass objectB = (MyClass)objectA.Clone();
        objectA.val = 10;
        objectB.val = 20;
        objectB.list[0] = 20;
        Console.WriteLine("objectA.val = {0}", objectA.val);
        Console.WriteLine("objectA.list[0] = {0}", objectA.list[0]);
        Console.WriteLine("objectB.val = {0}", objectB.val);
        Console.WriteLine("objectB.list[0] = {0}", objectB.list[0]);
        Console.ReadKey();
    }
}

output:

objectA.val = 10;
objectA.list[0] = 20;
objectB.val = 20;
objectB.list[0] = 20;

My question is: I have cloned the objectA to objectB, for value type (val) the output is as expected objectA is having 10 and objectB is having 20.

But for reference type like List the output is not as expected. I am getting objectA.list[0] as 20 and objectB.list[0] as 20. I was expecting objectA.list[0] as 1 and objectB.list[0] as 20.

Can someone please explain why clone is not working with List??

Nikolay Suvandzhiev
  • 8,465
  • 6
  • 41
  • 47
Raja Kondla
  • 278
  • 3
  • 11

2 Answers2

0

From msdn website:

The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.

If you want to copy reference types you have to do a deep cloning. Take a look at these:

How do you do a deep copy of an object in .NET (C# specifically)?

Deep cloning objects

Community
  • 1
  • 1
FCin
  • 3,804
  • 4
  • 20
  • 49
0

MemberwiseClone is a shallow copy (see https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.110).aspx). As expected, value types remain value types when copied. Therefore, changing the value of your cloned object does not change the value of your original. This is not the case for reference types. A shallow copy simply copies the reference over, so changing the cloned object will change the original as well. You need to implement your own deep cloner. You can find a generic solution or implement your own that works for every object type. A deep clone will create new instances of reference types instead of simply copying over the reference.

Tom
  • 2,360
  • 21
  • 15