string s1, s2;
case #1:
s1 = "Tom";
s2 = "Tom";
MessageBox.Show(string.Format("Is s2 the same reference as s1?: {0}", (Object)s2==(Object)s1));
case #2:
s1 = new string('t', 2);
s2 = new string('t', 2);
MessageBox.Show(string.Format("Is s2 the same reference as s1?: {0}", (Object)s2==(Object)s1));
For case#1, we will see the s2 is the same reference as s1.
For case#2, we will find the s2 is not the same reference as s1.
Explain:
MSDN topic for string.IsIntern() method:
The common language runtime automatically maintains a table, called the "intern pool", which contains a single instance of each unique literal string constant declared in a program, as well as any unique instance of String you add programmatically.
The intern pool conserves string storage. If you assign a literal string constant to several variables, each variable is set to reference the same constant in the intern pool instead of referencing several different instances of String that have identical values.
MSDN topic for string.Intern() method:
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.
For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable.
The Intern method uses the intern pool to search for a string equal to the value of str. If such a string exists, its reference in the intern pool is returned. If the string does not exist, a reference to str is added to the intern pool, then that reference is returned.
Summary:
The common languange runtime maintains the intern pool table for string constants only, not suitable for new constructed string by "new string()" or "new StringBuilder()", so if two string variables were assigned to same constant, then they refer to the same object in memory, otherwise they refer to which there are two different objects with same string value in memory.