1

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?

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Monzingo
  • 391
  • 1
  • 7
  • 17

2 Answers2

5

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:

Community
  • 1
  • 1
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
  • so what does the actual instantiation look like since you are instantiating something from something else (clone)? – Monzingo Oct 27 '16 at 17:59
1

That happens because the model.TransferedTransfers object is passed by reference, not by value. the variable completedSecond and transferedTransfers both points to model.CompletedTransfers. Also be aware of naming smells (transferedTranfers)

Stormhashe
  • 704
  • 6
  • 16