2

I'm using this function for a key in C#'s hash map like class, "Dictionary".

x, y and z are Int16.

public override int GetHashCode()
{
    return (x << 16) | (UInt16)y;
}

How could I extend this to using all 3 variables?


See What is the best algorithm for an overridden System.Object.GetHashCode? for the even more general case with any number of variables, of any type.

Community
  • 1
  • 1
alan2here
  • 3,223
  • 6
  • 37
  • 62
  • 2
    Please, please, please, DON'T use the accepted answer. Use the answer within the duplicate question above! The problems of the accepted one are endless (tend to 0, tend to 0xffff..., same hash for different objects, unbalanced hashes, etc.). – Oliver May 29 '12 at 07:23
  • Isn't having the same code for different objects unavoidable for three Int16 in an Int32? – alan2here Jun 08 '12 at 16:54

1 Answers1

2

For three variables x, y, z of any type, the standard method is as follows:

return x.GetHashCode() ^ y.GetHashCode() ^ z.GetHashCode();

^ is the XOR operator.

You can incorporate additional variables into your method using the XOR operator as well.

GregRos
  • 8,667
  • 3
  • 37
  • 63