After executing this piece of code:
int a = 50;
float b = 50.0f;
Console.WriteLine(a.GetHashCode() == b.GetHashCode());
We get False
, which is expected, since we are dealing with different objects, hence we should get different hashes.
However, if we execute this:
int a = 0;
float b = 0.0f;
Console.WriteLine(a.GetHashCode() == b.GetHashCode());
We get True
. Both obejcts return the same hash code: 0
.
Why does this happen? Aren't they supposed to return different hashes?
From MSDN Documentation:
The
GetHashCode
ofSystem.Int32
works like:Which of course with this being
0
, it will return0
.System.Single
's (float
is alias)GetHashCode
is:Like you see, at
0f
it will return0
.Program used is ILSpy.
Why should they? Hash codes are a finite set; as many as you can fit in an
Int32
. There are many many doubles that will have the same hash code as any given int or any other given double.Hash codes basically have to follow two simple rules:
Nothing obliges two objects that are not equal to have different hash codes; it is mathematically impossible.
Objects that are conceptually equal are obligated to return the same hashes. Objects that are different are not obligated to return different hashes. That would only be possible if there were less than 2^32 objects that could ever possibly exist. There are more than that. When objects that are different result in the same hash it is called a "collision". A quality hash algorithm minimizes collisions as much as possible, but they can never be removed entirely.