7

I am writing a EqualityComparer for a LINQ distinct expression and I am not too sure about the GetHashCode overload method. Would the below code be correct? The Id property is a long primitive.

public int GetHashCode(Deal obj)
{
   return ((int)obj.Id) ^ ((int)(obj.Id >> 32)); ;
}
Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
yulun
  • 260
  • 1
  • 6
  • 21
  • 6
    The answer depends on what you are comparing in the `Equals` method. Why not just `return obj.Id.GetHashCode()`? – Mike Zboray Nov 06 '12 at 04:16
  • I am just comparing with == operator for Equals method. I do not really need the hashcode in my context but I was just hoping to get clarification on the long primitive since there is a loss in precision. – yulun Nov 06 '12 at 05:53
  • 1
    comparing what with `==`? the `Id`? If so you are fine although `obj.Id.GetHashCode()` would be simpler. My point is that there are certain invariants `GetHashCode` and `Equals` must satisfy as part of the `IEqualityComparer` contract. In particular, `GetHashCode(x) != GetHashCode(y)` implies `Equals(x, y)` is false. The LINQ `Distinct` method requires both to be implemented correctly. Eric Lippert has an exhaustive list of guidelines if you are interested: http://blogs.msdn.com/b/ericlippert/archive/2011/02/28/guidelines-and-rules-for-gethashcode.aspx – Mike Zboray Nov 06 '12 at 07:08

1 Answers1

13

Probably you should check whether obj is not null. In case of null return 0. Honestly your implementation for long Id is completely the same as .NET Framework GetHashCode for long data type. In other words you can simply call obj.Id.GetHashCode() after not null checking.

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125