Equals vs GetHashCode when comparing objects

。_饼干妹妹 提交于 2019-11-27 22:22:11

Here's what you need to understand about the relationship between Equals and GetHashCode.

Hash codes are used by hashtables to quickly find a "bucket" in which an element is expected to exist. If elements are in two different buckets, the assumption is they cannot be equal.

The outcome of this is that you should view a hash code, for purposes of determining uniqueness, as a quick negative check: i.e., if two objects have different hash codes, they are not the same (regardless of what their Equals methods return).

If two objects have the same hash code, they will reside in the same bucket of a hash table. Then their Equals methods will be called to determine equality.

So GetHashCode must return the same value for two objects that you want to be considered equal.

The Distinct method will use the GetHashCode method to determine inequality between the items, and the Equals method to determine equality.

It first make a fast comparison using the hash code to determine which items are definitely not equal, i.e. have different hash codes, then it compares the items that have the same hash code to determine which are really equal.

In your implementation of the B class you have an inconsistent implementation of the GetHashCode and Equals method, so the comparison won't work properly. Your two B objects have different hash codes, so they won't be compared to each other. Two items that are considered to be equal should also return the same hash code.

If a class implements the IEquatable<T> interface, the Equals(T) method will be used, otherwise the Equals(object) method is used.

You always need to override them together and with compatible implementations. A hash-code match/mismatch means (respectively) "possible equality" and "non-equality". The hash-code by itself does not indicate equality. Hence, after a hash-code match is found (or used to create groups of values), Equals is still checked to determine a match.

If the two do not agree, you might never find matches.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!