Search code examples
c#booleangethashcode

GetHashCode for multiple boolean values


In the following StackOverflow question Jon Skeets answer specifies one good implementation is ...

// Note: Not quite FNV!
public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = (int) 2166136261;
        // Suitable nullity checks etc, of course :)
        hash = (hash * 16777619) ^ bool1.GetHashCode();
        hash = (hash * 16777619) ^ bool2.GetHashCode();
        return hash;
    }
}

What if the two fields are both bools. Would this still be a good implementation or would this be overkill? If this is overkill what is the recommended approach for implementing GetHashCode when all fields are bool types?

In my case I am only comparing two bools.


Solution

  • When you have fewer than thirty bool fields you can implement a perfect hashing scheme by treating each bool as a single bit in the value of hash code. By "perfect" I mean that hash equality would be equivalent to actual equality (as opposed to "ordinary" hashing schemes, in which actual equality implies hash equality, but not vice versa).

    The code would look like this:

    public override int GetHashCode() {
        var hash = 0;
        if (field1)
            hash |= 1<<0;
        if (field2)
            hash |= 1<<1;
        if (field3)
            hash |= 1<<2;
        if (field4)
            hash |= 1<<3;
        return hash;
    }