Creating a copy of an object in C#

afaolek picture afaolek · Jul 4, 2011 · Viewed 630k times · Source

Please have a look at the code below (excerpt from a C# book):

public class MyClass 
{
    public int val;
}
public struct myStruct 
{
    public int val;
}
public class Program 
{
    private static void Main(string[] args) 
    {
        MyClass objectA = new MyClass();
        MyClass objectB = objectA;

        objectA.val = 10;
        objectB.val = 20;

        myStruct structA = new myStruct();
        myStruct structB = structA;

        structA.val = 30;
        structB.val = 40;

        Console.WriteLine("objectA.val = {0}", objectA.val);
        Console.WriteLine("objectB.val = {0}", objectB.val);
        Console.WriteLine("structA.val = {0}", structA.val);
        Console.WriteLine("structB.val = {0}", structB.val);

        Console.ReadKey();
    }
}

I understands it produces the output below:

objectA.val = 20
objectB.val = 20
structA.val = 30
structB.val = 40

The last two lines of the output I have no problem with, but the first two tell me that objectA and objectB are pointing to the same memory block (since in C#, objects are reference types).

The question is how do make objectB, a copy of objectA so that it points to a different area in memory. I understand that trying to assign their members may not work since those members may be references, too. So how do I go about making objectB a completely different entity from objectA?

Answer

BugFinder picture BugFinder · Jul 4, 2011

You could do:

class myClass : ICloneable
{
    public String test;
    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

then you can do

myClass a = new myClass();
myClass b = (myClass)a.Clone();

N.B. MemberwiseClone() Creates a shallow copy of the current System.Object.