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 ?