Search code examples
c#wildcardhashcodeiequatable

Implement GetHashCode on a class that has wildcard Equatability


Suppose I want to be able to compare 2 lists of ints and treat one particular value as a wild card.

e.g. If -1 is a wild card, then

{1,2,3,4} == {1,2,-1,4} //returns true

And I'm writing a class to wrap all this logic, so it implements IEquatable and has the relevant logic in public override bool Equals()

But I have always thought that you more-or-less had to implement GetHashCode if you were overriding .Equals(). Granted it's not enforced by the compiler, but I've been under the impression that if you don't then you're doing it wrong.

Except I don't see how I can implement .GetHashCode() without either breaking its contract (objects that are Equal have different hashes), or just having the implementation be return 1.

Thoughts?


Solution

  • This implementation of Equals is already invalid, as it is not transitive. You should probably leave Equals with the default implementation, and write a new method like WildcardEquals (as suggested in the other answers here).

    In general, whenever you have changed Equals, you must implement GetHashCode if you want to be able to store the objects in a hashtable (e.g. a Dictionary<TKey, TValue>) and have it work correctly. If you know for certain that the objects will never end up in a hashtable, then it is in theory optional (but it would be safer and clearer in that case to override it to throw a "NotSupportedException" or always return 0).

    The general contract is to always implement GetHashCode if you override Equals, as you can't always be sure in advance that later users won't put your objects in hashtables.