Search code examples
c#clone

memberwiseclone in C# - system.object


MemberwiseClone() will create shallow copy, which will do a bit-by-bit copy of a value type and only copy the references of a reference type. We would need to create a deep copy to have an independent copy of a reference type. This is ok. I get this. Now my question is: why does a System.Object variable react differently when MemberwiseClone() is called?

Eg:

Public class Test
{
    public int x;
    public object obj;

    public Test MyClone()
    {
         return (Test) this.MemberwiseClone();
    }
}

Now access this in my Main method:

public static void Main()
{
    Test obj1 = new obj1;
     obj1.x = 1;
     obj1.obj = "x";

    Test obj2 = obj1.MyClone();
    obj2.obj = "y" 
}

Should this not change the value of obj1.obj to y? Since obj is an instance of System.Object which is obviously a reference type. But it does not change - obj1.obj gives x and obj2.obj gives y. Why is this?


Solution

  • It's because you don't change state of field obj. You assign it.

    public static void Main()
    {
        Test obj1 = new obj1;
         obj1.x = 1;
         obj1.obj = new List<string> {"x"};
    
        Test obj2 = obj1.MyClone();
        ((List<string>) obj2.obj).Add("y"); //now it contains {x, y} in obj1 and obj2
    }