How can I make a hashcode for a custom data structure?

If well this is not the best way, it can be a good enough approach:

public override int GetHashCode()
{
   return string.Format("{0}-{1}-{2}-{3}", X, Y, Face, Shell).GetHashCode();
}

Update: Take a look at this article: http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/


Basically, when writing hashcode functions, you need to make sure that:

  • you don't have stale hashcodes (i.e. the state of the object shouldn't change after a hashcode has been generated, such that the hashcode would change if regenerated)
  • objects with equal values return the same hashcodes
  • the same object always returns the same hashcode (if it's not modified) -- deterministic

Also, it's great, but not necessary, if:

  • your hashcodes are uniformly dispersed over the possible values (source: Wikipedia)

You don't need to ensure that different objects return different hashcodes. It's only frowned upon because it can decrease performance of things like Hashtables (if you have lots of collisions).

However, if you still want your hashcode function to return unique values, then you want to know about perfect hashing.

Tags:

C#

Hash