Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Same Object have to Same HashCode?

Let's assume I have two objects called K and M

if(K.Equals(M))
{

}

If that's true, K and M always has the same HashCode ?

Or It depends on the programming language ?

like image 886
Soner Gönül Avatar asked Aug 01 '11 13:08

Soner Gönül


2 Answers

If that's true, K and M always has the same HashCode ?

Yes.

Or rather it should be the case. Consumers of hash codes (eg. containers) can assume that equal objects have equal hash codes, or rather unequal hash codes means the objects are unequal. (Unequal objects can have the same hash code: there are more possible objects than hash codes so this has to be allowed.)

Or It depends on the programming language ?

No

like image 26
Richard Avatar answered Sep 18 '22 03:09

Richard


The contract for GetHashCode() requires it, but since anyone can make their own implementation it is never guaranteed.

Many classes (especially hashtables) require it in order to behave correctly.

If you are implementing a class, you should always make sure that two equal objects have the same hashcode.

If you are implementing an utility method/class, you can assume that two equal objects have the same hashcode (if not, it is the other class, not yours, that is buggy).

If you are implementing something with security implications, you cannot assume it.

like image 142
Rasmus Faber Avatar answered Sep 22 '22 03:09

Rasmus Faber