A "comparison" should mean "equal":
string first =
string second =
if (first == second)
Trivial, isn't it? Now, it's good to know, that 1) string is a reference type, but quite unusual type: is perfectly simulates "value semantics"; 2) for every reference type, there can be two (or three) different equivalences; referential and "semantic"; the referential equivalence is absolute and is returned by the method
object.ReferenceEquals
while "semantic" equivalence is defined by the virtual instance method
object.Equals
which can be overridden to change the "semantic" equivalence. It stands for all types, not only classes. Also, in any type one can re-redefine the operators "==" and "!=" (only both of them!) which affect comparison just using this operators, specifically. Mismatch between "==", "!=" and <code>object.Equals</code> is possible and would present a pathological case, so elementary requirements of sanity demand matching result of "semantic" comparison.
See
http://msdn.microsoft.com/en-us/library/system.object.aspx[
^].
Now, what's so unusual with strings? The CLR 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. So, an instance of a literal string with a particular value only exists once in the system.
There is a method to make sure that the semantic equivalence of the strings would cause referential equivalence. This is called
interning. See the static methods
System.String.IsInterned
and
System.String.Inter
. See the explanations and a code sample here:
http://msdn.microsoft.com/en-us/library/system.string.intern.aspx[
^].
—SA