Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading