string s1 = \"test\";
string s5 = s1.Substring(0, 3)+\"t\";
string s6 = s1.Substring(0,4)+\"\";
Console.WriteLine(\"{0} \", object.ReferenceEquals(s1, s5)); //Fa
The CLR doesn't intern all strings. All string
literals are interned by default. The following, however:
Console.WriteLine("{0} ", object.ReferenceEquals(s1, s6)); //True
Returns true
, since the line here:
string s6 = s1.Substring(0,4)+"";
Is effectively optimized to return the same reference back. It happens to (likely) be interned, but that's coincidental. If you want to see if a string is interned, you should use String.IsInterned()
If you want to intern strings at runtime, you can use String.Intern
and store the reference, as per the MSDN documentation here: String.Intern Method (String). However, I strongly suggest you not use this method, unless you have a good reason to do so: it has performance considerations and potentially unwanted side-effects (for example, strings that have been interned cannot be garbage collected).