The second ReferenceEquals call returns false. Why isn't the string in s4 interned? (I don't care about the advantages of StringBuilder over string concatenation.)
string s1 = "tom";
string s2 = "tom";
Console.Write(object.ReferenceEquals(s2, s1)); //true
string s3 = "tom";
string s4 = "to";
s4 += "m";
Console.Write(object.ReferenceEquals(s3, s4)); //false
When I do String.Intern(s4);
, I still get false.
Here, both s3 and s4 are interned but their references are not equal?
string s3 = "tom";
string s4 = "to";
s4 += "m";
String.Intern(s4);
Console.WriteLine(s3 == s4); //true
Console.WriteLine(object.ReferenceEquals(s3, s4)); //false
Console.WriteLine(string.IsInterned(s3) != null); //true (s3 is interned)
Console.WriteLine(string.IsInterned(s4) != null); //true (s4 is interned)
The Intern method uses the intern pool to search for a string equal to the value of str. If such a string exists, its reference in the intern pool is returned. If the string does not exist, a reference to str is added to the intern pool, then that reference is returned.
– Caphaitien