(You are currently looking at the second edition version of this page. This page is also available for the third
and first editions.)
P79: GetHashCode should almost always be unchecked
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()
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.