SYSK 114: String Interning

What do you think is the value of variable result in the code below:

string x = "some string here";

bool result = Object.ReferenceEquals("some string here", x);

 

Given that the data type stringis a reference type, it may come as a surprise to some, that the value is True.  This behavior is due to so called string interning .

The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.

 

Consider another example:

string s1 = "MyTest";

string s2 = new StringBuilder().Append("My").Append("Test").ToString();

string s3 = String.Intern(s2); // Retrieve the system's reference to the specified String.

bool result1 = Object.ReferenceEquals(s1, s2);

bool result2 = Object.ReferenceEquals(s1, s3);

 

Question: what is the value of result1 and result2?

 

Note:   The String.Intern method uses the intern pool to search for a string equal to the value of passed in string. If such a string exists, its reference in the intern pool is returned. If the string does not exist, a reference to it is added to the intern pool, then that reference is returned.

 

In comparison, String.IsIntern method returns null reference if the string is not found in the intern pool.

 

Answer: result1 is false since s1 and s2 refer to different objects; result2 is true since s1 and s3 refer to the same string.

 

One more piece of info:  CLR stores one string for a given literal across all the application domains.

 

 

References:

ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.en/cpref2/html/M_System_String_Intern_1_16219e3a.htm