Search code examples
c#unit-testingtddgethashcode

C#: How would you unit test GetHashCode?


Testing the Equals method is pretty much straight forward (as far as I know). But how on earth do you test the GetHashCode method?


Solution

  • Test that two distinct objects which are equal have the same hash code (for various values). Check that non-equal objects give different hash codes, varying one aspect/property at a time. While the hash codes don't have to be different, you'd be really unlucky to pick different values for properties which happen to give the same hash code unless you've got a bug.