Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should .GetHashCode() return same value for two objects having different refences in the memory?

I need to override Equals() method for one of my types but it seems I have to also override GetHashCode() method.

I am not sure:

If I have type Animal and if I have 2 instances of Animal which are basically the same(equal)Cats; like:

Animal cat_01 = new Animal("Kitty", "Pink");
Animal cat_02 = new Animal("Kitty", "Pink");

Should I implement the GetHashedCode() to retirn same value for both cas_01 and cat_02 eventhough they represent different references in the memory?

Is it the way GetHashCode() shuold work?

Thanks

like image 747
pencilCake Avatar asked Feb 24 '23 01:02

pencilCake


1 Answers

MSDN says:

If two objects compare as equal, the GetHashCode method for each object must return the same value.

So yes, GetHashCode should return the same value for both instances.

You can still use Object.ReferenceEquals if you want to see if they refer to the same object.

like image 135
Botz3000 Avatar answered Apr 27 '23 12:04

Botz3000