An answer to this question mentions that the immutable
characteristic of string
helps in achieving string interning.
Can anyone please explain how the characteristic of being immutable helps in achieving interning?
If String
were a mutable type, it simply couldn't be interned. There's no point in keeping a pool of objects if they can be mutated... you wouldn't be able to rely on what you got out of the pool being the string you were interested in (at least by the time you used it).
Imagine:
string x = "foo";
string y = "foo";
// x and y are references to the same object...
x.MutateTo("bar"); // This doesn't change which object y refers to...
Console.WriteLine(y); // This would have to print "bar" - eek!
See more on this question at Stackoverflow