Generates a hash code for the current instance.
A int containing the hash code for the current instance.
object.GetHashCode serves as a hash function for a specific type.
All implementations of object.GetHashCode are required to ensure that for any two object references x and y, if x.Equals(y) == true, then x.GetHashCode() == y.GetHashCode().
Hash codes generated by object.GetHashCode need not be unique.
Implementations of object.GetHashCode are not permitted to throw exceptions.
The object.GetHashCode implementation attempts to produce a unique hash code for every object, but the hash codes generated by this method are not guaranteed to be unique. Therefore, object.GetHashCode can generate the same hash code for two different instances.
Example 1
In some cases, object.GetHashCode is implemented to simply return an integer value. The following example illustrates an implementation of int.GetHashCode , which returns an integer value:
C# Example
using System;
public struct Int32 {
int value;
//other methods...
public override int GetHashCode() {
return value;
}
}
Example 2
Frequently, a type has multiple data members that can participate in generating the hash code. One way to generate a hash code is to combine these fields using an xor (exclusive or) operation, as shown in the following example:
C# Example
using System;
public struct Point {
int x;
int y;
//other methods
public override int GetHashCode() {
return x ^ y;
}
}
Example 3
The following example illustrates another case where the type's fields are combined using xor (exclusive or) to generate the hash code. Notice that in this example, the fields represent user-defined types, each of which implements object.GetHashCode (and should implement object.Equals(object) as well):
C# Example
using System;
public class SomeType {
public override int GetHashCode() {
return 0;
}
}
public class AnotherType {
public override int GetHashCode() {
return 1;
}
}
public class LastType {
public override int GetHashCode() {
return 2;
}
}
public class MyClass {
SomeType a = new SomeType();
AnotherType b = new AnotherType();
LastType c = new LastType();
public override int GetHashCode () {
return a.GetHashCode() ^ b.GetHashCode() ^ c.GetHashCode();
}
}
Avoid implementing object.GetHashCode in a manner that results in circular references. In other words, if AClass.GetHashCode calls BClass.GetHashCode, it should not be the case that BClass.GetHashCode calls AClass.GetHashCode.
Example 4
In some cases, the data member of the class in which you are implementing object.GetHashCode is bigger than a int. In such cases, you could combine the high order bits of the value with the low order bits using an XOR operation, as shown in the following example:
C# Example
using System;
public struct Int64 {
long value;
//other methods...
public override int GetHashCode() {
return ((int)value ^ (int)(value >> 32));
}
}