0

I was working on a c# program today and ended up having to chase a bug for quite some time.

I was trying to make a copy of an object change a few fields and send it on as well as the original

for example

Function(Object A)
{
    Object B = new Object();
    Object B = A;

    B.foo = "bar";

    Send(A);

    Send(B);
}

My program started treating A and B as the same object meaning that any changes to A would also change B and vise versa.

I know that the Object A and B are both referencing the same memory.

Is there a short hand way to ensure the line Object B = A references new memory thus creating different objects. Or is the only way to create a copy constructor in my Object and create B with Object B = new Object(A)

eg:

Object(Object a){
   foo = a.foo;
   ...
}

Basically i just what to know more about how C# handles object references and memory allocations. Big subject i know.

Paperwaste
  • 665
  • 2
  • 6
  • 14

3 Answers3

3

You can call the protected MemberwiseClone method, which will make a shallow copy of all the object. If you can modify the class of the object, you can even create a public Clone method that delegates to this. And if you're willing to use structs instead of classes, any assignment will create a copy. This is because structs are value types, and assigning one value type variable to another creates a copy.

With regard to MemberwiseClone, note the part where I said "shallow." Value type fields will be copied, but reference type fields will still refer to the same underlying objects.

Tim Destan
  • 2,028
  • 12
  • 16
0

Another way is serialization. You serialize original object and deserialize in another object. C# support the approach widely.

0

There are 2 objects present in your code. There is the one passed in via the parameter A, and the one instantiated on line 3. The second one is discarded immediately when you assign to B. B now holds a reference to the same object that variable A references. When you update its foo property through the B reference, this change is visible when you access it via the A reference.

If you want B to refer to a copy of what is in A, you can either define and use a copy constructor (B = new SomeClass(A)) or define and use a Clone function (B = A.Clone()). After either of these operations, A and B will refer to different object instances. There are also solutions involving structs ("value types") but that's generally not what a beginner is looking to do. Outside of that, just remember that B = A doesn't create a new object.

bmm6o
  • 6,187
  • 3
  • 28
  • 55