C# Strings – Immutable String in Array, Reference Type vs Value Type

arraycreferencestringsvalue-object

Trying to understand strings better in C#

Are these assertions correct?

  • string is immutable
  • string is reference type but behaves like value type

For these code samples…

string x = "one"   

(creates string instance holding "one" in memory)

x = "two"   

(destroys "one" instance and creates new string instance holding "two" in memory, even though it is using the same variable x)

If the above are correct, what happens in a string array when one index value changes?

string[] array = new string[2];

array[0] = "boo";   (string "boo" created and held in 0 index)
array[1] = "shoo";

array[0] = "moo";  

Does the last assignment create an entire new array to change boo to moo? My best "guess" is that the array holds pointers so that array[0] simply points to the new string instance that holds "moo". Is this correct? If not, could someone please clarify, thanks.

Best Answer

You have to be careful with some of the assumptions you are making about strings. The CLR has a "a table, called the intern pool, which contains a single instance of each unique literal string constant declared in a program". So what is really happening in your examples is:

string x = "one" // x references the "one" constant in the intern pool
x = "two" // x now references the "two" constant in the intern pool

array[0] = "boo"; // array[0] references the "boo" constant in the intern pool
array[1] = "shoo"; // array[1] references the "shoo" constant in the intern pool
array[0] = "moo"; // array[0] now references the "moo" constant in the intern pool
Related Topic