Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why some identical strings are not interned in .NET?

Tags:

string

c#

.net

string s1 = "test";
string s5 = s1.Substring(0, 3)+"t"; 
string s6 = s1.Substring(0,4)+"";   
Console.WriteLine("{0} ", object.ReferenceEquals(s1, s5)); //False
Console.WriteLine("{0} ", object.ReferenceEquals(s1, s6)); //True

Both the strings s5 and s6 have same value as s1 ("test"). Based on string interning concept, both the statements must have evaluated to true. Can someone please explain why s5 didn't have the same reference as s1?

like image 301
DivideByzero Avatar asked Jan 11 '16 19:01

DivideByzero


1 Answers

You should get false for calls of ReferenceEquals on string objects that are not string literals.

Essentially, the last line prints True by coincidence: what happens is that when you pass an empty string for string concatenation, library optimization recognizes this, and returns the original string. This has nothing to do with interning, as the same thing will happen with strings that you read from console or construct in any other way:

var s1 = Console.ReadLine();
var s2 = s1+"";
var s3 = ""+s1;
Console.WriteLine(
    "{0} {1} {2}"
,   object.ReferenceEquals(s1, s2)
,   object.ReferenceEquals(s1, s3)
,   object.ReferenceEquals(s2, s3)
);

The above prints

True True True

Demo.

like image 138
Sergey Kalinichenko Avatar answered Oct 31 '22 21:10

Sergey Kalinichenko