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)); ;
}
3
  • 6
    The answer depends on what you are comparing in the Equals method. Why not just return obj.Id.GetHashCode()? Nov 6, 2012 at 4: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 6, 2012 at 5: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<T> 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: blogs.msdn.com/b/ericlippert/archive/2011/02/28/… Nov 6, 2012 at 7:08

1 Answer 1

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.