If strings in .NET are reference types, in the below code, why doesn't string2 change to "hi" after string1 is changed?
static void IsStringReallyAReference()
{
string string1 = "hello";
string string2 = string1;
Console.WriteLine("-- Strings --");
Console.WriteLine(string1);
Console.WriteLine(string2);
string1 = "hi";
Console.WriteLine(string1);
Console.WriteLine(string2);
Console.Read();
}
/*Output:
hello
hello
hi
hello*/
That is because C# strings are immutable types, meaning that you cannot change the value of the instance.
When you change the string's value you are actually creating a new string and changing the reference to point to the new string after which your two reference variables no longer refer to the same string instance, one refers to the original string while the other refers to the new string instance with the new value.