#68 – String Equality

The default behavior for reference type equality dictates that two variables are equal only if they point to the same object.  However, the System.String class (string) overrides this.  Two string variables are equal if the two strings pointed to are equal (i.e. they have the same value).

 string s1 = "Popeye";
 string s2 = Console.ReadLine();   // Enter "Popeye" here

 bool b = (s1 == s2);    // True because contents of strings are equal

So, although s1 and s2 point to two different string objects in memory, the equality operator returns true because the values of the two strings are equal.

Advertisement