1

One of my C# books (C# 3.0 Cookbook by Hillyard and Teilhet) in giving an example of a Square class writes the GetHashCode as

public override int GetHashCode ( ) 
{
    return this.Height.GetHashCode() | this.Width.GetHashCode();
}

I'm wondering why this is considered a good hash code. Becuase the table for an | operation is

x | y | x OR y
--------------
0 | 0 |   0
1 | 0 |   1 
0 | 1 |   1
1 | 1 |   1

which means that 3/4 of the time the result of the operation is 1. So if you have miscellaneous ints w, x, y, z that means the chance that w | x == y | z is not as small as it could be (if ^ was used, for example).

Is my understanding of this corret? Or is there a good reason why | is used for the hashing function?

user6048670
  • 2,861
  • 4
  • 16
  • 20
  • 1
    It's not a good hash function. `^` would be better. However, keep in mind that `GetHashCode()` is just the first step in equality so returning a constant would also be an acceptable (but not good) hash code. – Enigmativity Mar 13 '16 at 06:27
  • @Enigmativity That's for confirming what I thought was the case – user6048670 Mar 13 '16 at 06:28
  • Welcome to SO, Hillary:) I suspect nobody except Hillyard and Teilhet can explain why they prefer OR over XOR. I would use the latter, but you can do some benchmarking against `Distinct()` over a collection for example. – Diligent Key Presser Mar 13 '16 at 06:28
  • 1
    I will just put this here http://stackoverflow.com/q/5889238/3909293 – Diligent Key Presser Mar 13 '16 at 06:36
  • 2
    While I don't know the context, `Square` sounds like the width and height ought to be equal. In that case, XOR would be a particularly poor hash combinator because it would just be zero. – harold Mar 13 '16 at 10:17

1 Answers1

4

That is a horrible, horrible hash function, for exactly the reason you mention. Certainly a mistake (or you should find a new book!). You should submit it to the book's errata page:

http://www.oreilly.com/catalog/errata.csp?isbn=9780596516109

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87