1

Sure, hascodes are used in hastables and collections but what about that:

class TwoDPoint : System.Object{

   public readonly int x, y;

   //...left out some code

   public override int GetHashCode(){
      return x ^ y;
   }
}

Source: https://msdn.microsoft.com/en-us/library/ms173147(VS.80).aspx
The snipped above directed me to the following sentence:

You should not assume that equal hash codes imply object equality.

Source: https://msdn.microsoft.com/de-de/library/system.object.gethashcode(v=vs.110).aspx

What I wonder is if we shouldn't always check for object equality after two hash codes match. Consider the following two dots:

P1.x = 2; P1.y = 4; Hash = 16
and
P2.x = 4; P2.y = 2; Hash = 16

  • If I only check the hash before inserting an item into a hashtable wouldn't that be a huge problem?
  • Or is the this function maybe just used to provide a more performant way of checking "simmilarity" but always requires an equality check after a match?
  • Or should I not care and just use the hashcode and assume it doesn't matter?
Noel Widmer
  • 4,444
  • 9
  • 45
  • 69
  • 1
    Yes, you *should* always check for object equality if two hash codes match. Items that are equal must have the same hash code, but the *reverse* is not necessarily true. – Charles Mager Jan 16 '16 at 12:45
  • The hash code is used to determine the "bucket" to store or look up an object in a hashed collection. So you, from user code, should not use the hash code to determine object (in)equality, just as the MSDN page tells you. Maybe explain why you want to _"check the hash before inserting an item into a hashtable"_ and so on. – CodeCaster Jan 16 '16 at 12:51
  • @CodeCaster I don't want to call GetHashCode. I was just wondering how the method is used by the .NET Framework. – Noel Widmer Jan 16 '16 at 14:23

0 Answers0