#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.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #68 – String Equality

  1. Pingback: #479 – Identical String Literals Are Stored in Same Object « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: