C# in Depth

Cover of C# in Depth
Order now (3rd edition)

GetHashCode should almost always be unchecked

Chapter 3: Parameterized typing with generics: P79

Created: 9/3/2011
Last updated: 9/3/2011

I don't talk about checked/unchecked blocks much if at all in C# in Depth, but I do give an example of a Pair class which overrides GetHashCode. In the interests of brevity, I left this method with the "default" checked-ness of the project, but in reality hash code generation should almost always be unchecked:

public override int GetHashCode()
{
    unchecked
    {
        // Hash generation here
    }
}

Of course if you use helper methods for all the arithmetic and they're unchecked, that means you don't need to worry about your method itself.

Hash generation should be unchecked because in some ways you don't care about the value - or at least, you don't care about it (much) as a number with a magnitude. It's just a way of getting some "random" bits which can be used to quickly narrow down possible matches. There are some properties which are handy for hashes to have, but most of the time a simple "repeated add and multiply" approach works just fine, and letting the value overflow in the normal unchecked way is fine.