In order to understand LINQ’s Except method, we first need to understand GetHashCode method.

What is hash code?

  1. A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary<TKey, TValue> class, the Hashtable class, or a type derived from the DictionaryBase class. [1]


What is the most important properties of hash code?

  1. Two objects that are equal return hash codes that are equal.
  2. However, the reverse is not true: equal hash codes do not imply object equality, because different (unequal) objects can have identical hash codes.  [1]


Why do we need hash code?

  1. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.
  2. Providing a good hash function on a class can significantly affect the performance of adding those objects to a hash table.
    1. In a hash table with keys that provide a good implementation of a hash function, searching for an element takes constant time (for example, an O(1) operation).
    2. In a hash table with a poor implementation of a hash function, the performance of a search depends on the number of items in the hash table (for example, an O(n) operation, where n is the number of items in the hash table). [1]


What is the relationship between GetHashCode and LINQ?

  1. A lot of the LINQ sequence operators use hash tables internally. If you want your type to play well with LINQ, take care of its GetHashCode method. [2]


The relationship and call sequence between GetHashCode and Equals?

Your item will be used as a key in a dictionary, or HashSet<T>, etc – since this is used (in the absence of a custom IEqualityComparer<T>) to group items into buckets. If the hash-code for two items does not match, they may never be considered equal (Equals will simply never be called). [3]

The GetHashCode() method should reflect the Equals logic; the rules are [3]:

  • if two things are equal (Equals(...) == true) then they must return the same value for GetHashCode()
  • if the GetHashCode() is equal, it is not necessary for them to be the same; this is a collision, and Equals will be called to see if it is a real equality or not.

In other words, the hash code is used as a first-step in determining equality only, and should never be used as a de-facto determination as to whether two objects are equal.

  1. If two objects’ hash codes are not equal then they are treated as not equal.
  2. If they have the same hash code, then they should then be checked for actual equality. [5]



  1. Object.GetHashCode Method ()
  2. Guidelines and rules for GetHashCode

  3. Why is it important to override GetHashCode when Equals method is overridden?

  4. Default implementation for Object.GetHashCode()