Home > Enterprise >  Changing value in array of objects
Changing value in array of objects

Time:08-12

I have a bit of code and I am confused with my observations

var arr = new Class[]
{
    new Class{Name = "First"},
    new Class{Name = "Second"}
};

var first = arr[0];

arr[0] = new Class { Name = "Third"};

Console.WriteLine(first.Name); //Name = First

class Class
{
    public string Name { get; set; }
}

At first , I thought that this code should write 'Third' because it is array of references to objects and we are changing arr[0] to 'Third' , but first variable has 'First' value after changing reference in the array.

I have assumption , that this happens because when we getting arr[0] we get reference by value , like if we pass object to some function we can change state of the object , but we can't change the entire object. That is why first variable continues to point on our object with name 'First'. I tried to prove this assumpition with this code

ref Class first = ref arr[0];

arr[0] = new Class { Name = "Third" };

Console.WriteLine(first.Name); //Name = Third

But i am not sure about it. Can someone proves or refutes ?

CodePudding user response:

Your assumption is correct. The variable first is still pointing at the object that was originally located at arr[0]. Updating arr[0] will simply update that array element only, what first is referring to is unchanged.

Taking inspiration from Dan Abramov's excelling Just Javascript series to explain variables and values, you can build a mental model of variables as "wires" that link variables to values. Your values here are Class object references. With this you can picture what's happening:

  • You create an array of two elements. This creates two objects in memory to store something (two values, with wires back to each array element variable).
  • You create the variable first which has a wire to arr[0]. first and arr[0] are now referring to the same value (object reference).
  • You assign arr[0] to a new object. This creates a value (object reference) and moves the wire connecting arr[0] from the old value to that new one.
  • The wire from first is untouched - it's still connected to the original value originally in arr[0] .

This mental model is for reference types, if your values are value types, then each use of new will create a new value and move the wire from the variable being assigned to that new value. There won't be any value with more than one wire connecting to it.

  • Related