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; }
source share