C# - Generic HashCode implementation for classes

后端 未结 3 1345
独厮守ぢ
独厮守ぢ 2021-01-02 05:17

I\'m looking at how build the best HashCode for a class and I see some algorithms. I saw this one : Hash Code implementation, seems to be that .NET classes HashCode methods

3条回答
  •  心在旅途
    2021-01-02 05:51

    Your Equals method is broken - it's assuming that two objects with the same hash code are necessarily equal. That's simply not the case.

    Your hash code method looked okay at a quick glance, but could actually do some with some work - see below. It means boxing any value type values and creating an array any time you call it, but other than that it's okay (as SLaks pointed out, there are some issues around the collection handling). You might want to consider writing some generic overloads which would avoid those performance penalties for common cases (1, 2, 3 or 4 arguments, perhaps). You might also want to use a foreach loop instead of a plain for loop, just to be idiomatic.

    You could do the same sort of thing for equality, but it would be slightly harder and messier.

    EDIT: For the hash code itself, you're only ever adding values. I suspect you were trying to do this sort of thing:

    int hash = 17;
    hash = hash * 31 + firstValue.GetHashCode();
    hash = hash * 31 + secondValue.GetHashCode();
    hash = hash * 31 + thirdValue.GetHashCode();
    return hash;
    

    But that multiplies the hash by 31, it doesn't add 31. Currently your hash code will always return the same for the same values, whether or not they're in the same order, which isn't ideal.

    EDIT: It seems there's some confusion over what hash codes are used for. I suggest that anyone who isn't sure reads the documentation for Object.GetHashCode and then Eric Lippert's blog post about hashing and equality.

提交回复
热议问题