konfortes
konfortes

Reputation: 99

C# Equals and GetHashCode

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.

Upvotes: 5

Views: 569

Answers (4)

Dennis_E
Dennis_E

Reputation: 8904

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

Upvotes: 9

dcastro
dcastro

Reputation: 68740

This is mathematics. The pigeonhole principle states that if you have 101 pigeons to put in 100 holes, than you will have to put 2 pigeons in the same hole.

As follows, if you have 2^64 possible longs, and 2^32 possible hashcodes (signed int), then you're bound to get the same hash code for different longs.

Upvotes: 4

AgentFire
AgentFire

Reputation: 9790

Well, since long is 8-byted and int is only 4, you can say there will be A LOT of hash code collisions.

For example, 5 and 4294967300 have the same hash code. Which is 5.

Upvotes: 2

Nick
Nick

Reputation: 25808

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.

Upvotes: 4

Related Questions