Should the GetHashCode () method take care of the null value specified as a parameter?

In some C # code, I use the linq GroupBy<TSource, TKey>() method with a custom IEqualityComparer<T> .

 GroupBy(x => x.SomeField, new FooComparer()); 

Field i, used as a grouping key, can be null . As a result, I had to add a few null checks in the Equals() method:

 public bool Equals(Foo x, Foo y) { if (x == null && y == null) return true; else if (x == null && y != null) return false; else if (x != null && y == null) return false; else return x.Id == y.Id; } 

Question: Should I do the same in the GetHashCode() function?

 public int GetHashCode(Foo obj) { if (obj == null) //is this really needed ? return default(int); // else return obj.Id; } 

I don’t understand something: even with the null keys represented in the GroupBy() method, GetHashCode() never called with the null object in the obj parameter. Can someone explain to me why? (is this just a “clean chance" because the GroupBy() method is implemented and the order of the elements that I give it?)


EDIT:

as caerolus pointed out, there are some special checks performed in the implementation of GroupBy() .

I checked in ILSpy and GroupBy() implemented using Lookup<TKey, TElement>

Here is the revelant function:

 internal int InternalGetHashCode(TKey key) { if (key != null) { return this.comparer.GetHashCode(key) & 2147483647; } return 0; } 
+4
source share
1 answer

According to IEqualityComparer<T>.GetHashCode :

ArgumentNullException
The obj type is a reference type, and obj is null .

So, this is part of the contract of this interface, and therefore you should take care. Throw it by throwing an ArgumentNullException if obj is null .

You should always stick to the interface, even if you suspect or can prove that the code will never touch parts that you don't need. Subsequently, changes may cause this code to depend on this behavior.

+5
source

All Articles