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

Advertisement

#413 – Check for Reference Equality Using Object.ReferenceEquals

You might encounter types that override both the == operator and the Equals method to check for value equality.

For example, a PersonHeight value type might behave this way.  Both checks return true in the example below.

            PersonHeight ph1 = new PersonHeight(5, 10);
            PersonHeight ph2 = new PersonHeight(5, 10);

            // Both == operator and Equals method are checking
            // for value equality
            bool check = ph1 == ph2;    // true
            check = ph1.Equals(ph2);    // true

If you want to do a reference equality check, you can always use the Object.ReferenceEquals method. This method cannot be overridden and always does a reference equality check–i.e. compares two object references to see if they refer to the same object.

            // Check for reference equality
            check = ReferenceEquals(ph1, ph2);      // false