Does string interning in C# guarentee you only get one copy of a static value?

Of course the answer is no, otherwise it wouldn’t be a very interesting post. The concept of interning is an attempt to save memory by allocating static values which match exactly to the same memory location, without regard to where they’re used in the application. But here’s in instance where it doesn’t quite work.

The String.Empty constant just contains the value “”. So logic would say that every value in the following code would point to the exact same location:

        static void Main(string[] args) {
            String t = "";
            String t1 = String.Empty;
            String t2 = String.Empty;
            String t3 = "";
            Console.WriteLine(t + t1 + t2 + t3);
        }

But, if you look at the disassembly, you find that the two values for “” were interned to one location (0226303Ch), and the String.Empty values were interned to another (0226102Ch):

String t = "";
00000033  mov         eax,dword ptr ds:[0226303Ch] 
00000039  mov         esi,eax 
String t1 = String.Empty;
0000003b  mov         eax,dword ptr ds:[0226102Ch] 
00000040  mov         edi,eax 
String t2 = String.Empty;
00000042  mov         eax,dword ptr ds:[0226102Ch] 
00000047  mov         dword ptr [ebp-48h],eax 
String t3 = "";
0000004a  mov         eax,dword ptr ds:[0226303Ch] 
00000050  mov         dword ptr [ebp-4Ch],eax