Why does the original string remain unchanged in example 1 and the original instance not get nulled in example 2, when the string property of an object instance is changed in example 3?
class A { public string property = "class a"; }
static void Main(string[] args)
{
//Example1
string var = "something";
string[] array = new string[] { var };
array[0] += " again";
// var is unchanged, contents in array slot zero are changed
//Example2
A instance = new A();
object[] array2 = new object[] { instance };
array2[0] = null;
// instance is also unchanged, contents in array slot zero are now null
//Example3
A anotherInstance = new A();
object[] array3 = new object[] { anotherInstance };
(array3[0] as A).property = " else";
// the *propery* of anotherInstance changes as expected
return;
}
When you assign a value in an array, you create a copy of the original value. You’re not creating a copy of the string itself, but a copy of the value of the “var” variable – which is a string reference. After that point of time, there’s no relationship between the variable and the array element – they happen to have the same value immediately afterwards, but they’re independent. Changing the array element to make it refer to a different object doesn’t change the value of the variable, or vice versa.
In particular, this line:
does not change the contents of the existing string. Instead, it creates a new string and assigns that reference to
array[0].Now in your “Example3” you aren’t changing the value of the array element itself – you’re changing the contents of the object that both
anotherInstanceandarray3[0]refer to. It’s like two people knowing about the same house – if one person paints the door red, the other person will see the red door too.This all has very little to do with arrays – you’d see the same effects with individual variables too. See my article on reference and value types for further information.