Monzingo Monzingo - 1 month ago 15
C# Question

Updating One Object Updates the Other somehow

I have two objects, yet when i update one, the other item with the same GUID gets updated as well even though i am trying to apply a new GUID so that i can separate them out.

var completedSecond = model.CompletedTransfers.First();
var transferedTransfers = model.TransferedTransfers.First();

if (transferedTransfers.Count != 0) {
transferedTransfers.RowId = Guid.NewGuid();
}


When i run this code, the two items have the same GUID, yet when i update the second one to have a new GUID, the first object also gets that new GUID. How is this possible?

Answer

You don't have 2 objects but 2 references to the same object in memory. In C# classes are reference types meaning that your completedSecond is referencing an object in memory, that in this case is the same as the object transferedTransfers is referenceing to.

In order to get 2 different object you need to instantiate a new object

  1. By implementing the ICloneable interface

    public class MyClass : ICloneable
    {
        public Guid Id { get; set; }
    
        public object Clone()
        {
            return new MyClass { Id = Id };
        }
    }
    
  2. Another way is to have a copy constructor:

    public class MyClass
    {
        public Guid Id { get; set; }
    
        public MyClass() { }
    
        public MyClass(MyClass other)
        {
            Id = other.Id;
        }
    }
    

Read this for the differences between the two ways: Copy constructor versus Clone()

In addition, when talking about coping of objects you have what is called deep-copy and shallow-copy. More on these you can find here:

Comments