Every object you ever created or used in .NET has GetHashCode method along with Equals, GetType, and ToString methods. This method is an instance method of an Object class from which any other class derives.
GetHashCode() method returns an integer that identifies an object instance. I also can repeat MSDN documentation but you can read it on your own.
The best way to explain it is to show an example. In my previous post I was using class Point as an example. I’m going to continue with this class. So let assume that we have class like this:
Next we want to use Point as a key in a Hashtable. Remember that the key of the Hasthable must be unique. In the code bellow we have two identical keys (line 2 & 4). We should expect ArgumentException.
However, no exception was thrown. There are two reasons why exception is not thrown:
- Equals() method that is also an instance method of Object class will always indicate that Point in line 2 and line 4 are different. This expected because two objects have different references.
- GetHashCode() method returns different number for these objects.
Try to execute code bellow:
You will get output similar to this one:
point1 Hash: 58225482
point2 Hash: 54267293
point1 equal to point2: False
You can see that we got different hash codes.
To solve this problem we override Equal() and GetHashCode() in our Point class.
First we override Equals() method:
You can see that I use ReferenceEquals() method that is static method of Object class. It checks if the specified objects are the same.
Next we override GetHashCode() method:
The whole Point would look like this:
Now if you try to execute the application the output should look exactly like this:
point1 Hash: 793
point2 Hash: 793
point1 equal to point2: True
Also if we try to add new Point(2, 3) twice, we get an ArgumentException as expected.