Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why string interned but has different references?

string s1 = "abc";
string s2 = "ab";
string s3 = s2 + "c";

Console.WriteLine(string.IsInterned(s3));           // abc
Console.WriteLine(String.ReferenceEquals(s1, s3));  // False

I just cannot understand why s3 interned, but ReferenceEquals was False.

Dose they have two copies in intern pool?

Thanks in advance.

like image 465
Lei Kan Avatar asked Mar 08 '14 14:03

Lei Kan


1 Answers

They are separate references. The string "abc" is interned because it is a literal string.

The expression s2 + "c" is compiled to string.Concat(s2, "c").. which results in a new (and separate) string reference.

like image 198
Simon Whitehead Avatar answered Oct 09 '22 11:10

Simon Whitehead