Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Make Types Hashable with GetHashCode()

Scenario/Problem:

You want to use your class as the key part in a collection that indexes values by unique keys. To do this, your class must be able to convert the “essence” of its values into a semi-unique integer ID.

Solution:

You almost always want to override GetHashCode(), especially with value types, for performance reasons. Generating a hash value is generally done by somehow distilling the data values in your class to an integer representation that is different for every value your class can have. You should override GetHashCode() whenever you override Equals().

public override int GetHashCode()
{
    //note: This is just a sample hash algorithm.
    //picking a good algorithm can require some
    //research and experimentation
    return (((int)_x ^ (int)_z) << 16) |
           (((int)_y ^ (int)_z) & 0x0000FFFF);
}
  • + Share This
  • 🔖 Save To Your Account