My understanding is that literals are automatically interend. Let’s take below code example.
string s = "x" + "y" + "z";
Console.WriteLine(String.IsInterned(s) ?? "Not Interned");
string ss = new string(new char[] { 'x', 'y', 'z' });
Console.WriteLine(String.IsInterned(ss) ?? "Not Interned");
string sss = new string(new char[] { 'a', 'b', 'c' });
Console.WriteLine(String.IsInterned(sss) ?? "Not Interned");
The output it as follows.
xyz
xyz
Not Interned
So from code example below strings s and ss proves that literals are automatically interened. I am not sure why same is not the case for string sss?
String interning is initially done by the compiler. Due to constant folding, it collapses
"x" + "y" + "z"into a single string instance"xyz", which is interned because it’s a string literal.Then when you create the second string instance at runtime, it equals the interned compile-time instance (but it’s still a different instance), so
IsInternedcan find that string and return it. You never explicitly interned a string value of"abc"and also never specified it as string literal in any way. That’s why it’s not interned by default.