#422 – How ReferenceEquals Behaves When Comparing Strings

The Object.ReferenceEquals method uses reference equality semantics, returning true if two variables refer to the same object in memory.

When comparing strings, you typically want value equality semantics, so you would not use ReferenceEquals.  In the example below, the string values are the same, but the strings are stored in different memory locations, so ReferenceEquals returns false.

            string s1 = "Bouffant";
            StringBuilder sb2 = new StringBuilder("Bouffant");
            bool compare = ReferenceEquals(s1, sb2.ToString());  // false

Because of the way that the compiler stores strings, ReferenceEquals might return true for two equivalent string constants stored in two different variables.  In the example below, the compiler stores just one copy of the string “Galoshes”.

            string s1 = "Galoshes";
            string s2 = "Galoshes";
            bool compare = ReferenceEquals(s1, s2);  // true

Even though ReferenceEquals returns true in this case, you should not rely on this behavior, but use Equals or the == operator to compare two strings.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #422 – How ReferenceEquals Behaves When Comparing Strings

  1. Aurifier says:

    Are you… waiting for the bus?

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: