There's a job interview question I encountered some days ago: How can 2 C# objects or primitive types have the same result for their un-overridden GetHashCode()
method but Equals()
false? I was directed to the primitive type long
and couldn't think of a solution for that.
The rule is that if Equals returns true, then GetHashCode must return the same value, but not the other way around.
Consider this: GetHashCode returns an int. The Type long has more possible values than the Type int. This means that more than one long value will produce the same hash code as another long value. This is called the Pigeon-Hole Principle: http://en.wikipedia.org/wiki/Pigeonhole_principle
A hashcode is a 32-bit integer - how are you going to get a unique hash for every 64-bit long?
A hash-code is supposed to be as-unique-as-possible in order to be as efficient as possible. Equality is a mathematical rule which can't be broken.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With