GetHashCode to Test Equality

Problem
You want to know if you should use the GetHashCode method to determine if two objects are equal.

Solution
Don’t use the value returned by the GetHashCode method to check if two objects are equal.

Comments
You can only come to one conclusion by comparing the hash codes of two objects. The conclusion is that objects with different hash codes are not the same. You never want to assume that two object variables with the same hash code point to the same object. This is because Object.GetHashCode is often overridden in derived types. The only version of the method you can rely on is in the Object class. The GetHashCode method’s implementation may change in future versions of the .NET Framework. This would cause types that don’t override GetHashCode to be potentially different.

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