#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

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

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 )

Connecting to %s

%d bloggers like this: