Search code examples
c#.nethashequalsgethashcode

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


Solution

  • 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.