Search code examples
c#.net

string interning vs address in memory


I have this code:

var a = "ab";
var b = string.Concat("a", "b");


Console.WriteLine(string.IsInterned(a)!=null); //True
Console.WriteLine(string.IsInterned(b)!=null); //True

Console.WriteLine(object.ReferenceEquals(a,b)); //False

So the string a is compile time and is by default interned. The second one I suspected should behave in the same way as would be "a"+"b" which would also be interned. This seems to be confirmed by string.IsInterned(string) methods which both return True. However the address in memory is different which is indicated by object.ReferenceEquals(object,object) returning False. If both strings are interned then shouldn't they be actually the same object in the string intern table so the same reference?


Solution

  • Now try:

    var c = string.IsInterned(b);
    Console.WriteLine(ReferenceEquals(a, c)); // spoiler: True
    Console.WriteLine(ReferenceEquals(b, c)); // spoiler: False
    

    It is telling you "yes, I do have an interned value that contains "ab"" - but that doesn't mean that the reference you passed in is itself interned - just that the contents "ab" exist in the interned list.