Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Equals and GetHashCode

Tags:

c#

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.

like image 416
konfortes Avatar asked Jun 23 '14 09:06

konfortes


2 Answers

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

like image 160
Dennis_E Avatar answered Oct 06 '22 02:10

Dennis_E


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.

like image 21
Nick Avatar answered Oct 06 '22 01:10

Nick