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
}