Creating a shallow copy of structures in C#

samar picture samar · Aug 2, 2013 · Viewed 9.8k times · Source

I tried to search for my answer and found them in regards to C and not C# so thought of posting it.

My question might be trivial here.

As per my understanding (in simple terms)

After Copying has completed

Shallow Copy -> main and copied object (reference or value type) should point to the same object in memory

DeepCopy -> main and copied object (reference or value type) should point to different objects in memory

Going ahead with this, I have a structure in C# and trying to make a shallow copy of the same. I tried using "MemberwiseClone" method but I guess it works only for reference types. For value types i think "MemberwiseClone" method will box it into an object and unbox it into a different memory address in the stack.

What i have tried is as below.

My question is how (if at all possible) can I create a shallow copy of a simple structure?

I hope my fundamentals are correct here and not talking rubbish. Please correct me if I am wrong in any of the statements I have made.

Regards,

Samar

struct MyStruct : ICloneable
{
    public int MyProperty { get; set; }

    public object Clone()
    {
        return this.MemberwiseClone();//boxing into object
    }
}


    private void btnChkStr_Click(object sender, EventArgs e)
    {
        MyStruct struct1 = new MyStruct();
        struct1.MyProperty = 1;

        //MyStruct struct2 = struct1; //This will create a deep copy
        MyStruct struct2 = (MyStruct)(struct1.Clone());//unboxing into structure hence allocating a different memory address
        struct2.MyProperty = 2;

        MessageBox.Show(struct1.MyProperty.ToString()); //still showing 1
    }

Answer

Kai Hartmann picture Kai Hartmann · Aug 2, 2013

Your expectation of what a deep copy vs a shallow copy does is not correct. A shallow copy copies all value types, and just the references of reference types. A deep copy copies all value types and all reference types.

So your struct already performs a shallow copy when doing:

MyStruct struct2 = struct1;

This code example (console application) shows, that changing a value of the object in the second struct changes also the value of the object in the first struct, because the object has just been copied by reference:

class Program
{
    static void Main(string[] args)
    {
        Test t1 = new Test();
        t1.i = 1;
        t1.o = new Klasse();
        t1.o.i = 1;

        Test t2 = t1;
        t2.i = 2;
        t2.o.i = 2;

        Console.WriteLine(t1.i.ToString());
        Console.WriteLine(t1.o.i.ToString());
        Console.WriteLine(t2.i.ToString());
        Console.WriteLine(t2.o.i.ToString());
        Console.Read();
    }
}

struct Test
{
    public int i;
    public Klasse o;
}

class Klasse
{
    public int i = 0;
}