Why does IEqualityComparer <T> have a GetHashCode () method?
IEqualityComparer in the System.Collections.Generic namespace has the following methods:
bool Equals(T x, T y); int GetHashCode(T obj); Since this inteface is used to verify the equality of objects, the first Equals method makes sense. But why do we also need to implement GetHashCode ? Why does it exist in the interface in the first place? When is it necessary and why?
I use it with the Enumerable.Distinct () method in the System.Linq namespace, and I am surprised to see that even GetHashCode() is called along with Equals() . What for? How does Distinct work?
For more on how Distinct (or at least a simple example implementation) works, see my Edulinq blog post ( old - 404
Simply put, a hash corresponding to a matching equality mapping makes it cheaper to create a collection of elements. This is useful in many situations - for example, Distinct , Except , Intersect , Union , Join , GroupJoin , GroupBy , ToLookup , etc.
GetHashCode used for HashTables , Dictionaries and others to optimize your search. Have a look here: http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx
Since Recommendations for redefining equal () and operators == (C # Programming Guide) :
It is recommended that any class that overrides Equals also overrides Object.GetHashCode.
This is due to the fact that hashtables etc. expect two identical objects to have the same hash code.
The goal of IEqualityComparer (Of T) is to allow the use of a comparison method that is semantically different from the default Object.Equals object, which can cause two objects to be considered equal even if Object.Equals considers them differently. Since equal objects must have the same hash codes and because EqualityComparer Equals methods are considered equal, but Object.Equals believes that unequal can have different hash codes, it is necessary that EqualityComparer use a different hash encoding.
A more interesting situation exists with IEquatable (Of T). It is expected that never report two objects equal if Object.Equals reports them unevenly. For any unsealed class to implement, IEquatable (Of T) is dangerous; too bad, there is no general restriction that would prohibit the use of unsealed classes.