0

I have a class similar to below:

class Abc
{
     public string A {get;set;}
     public string B {get;set;}
}

The criteria for equals is if any of A or B matches two objects of class Abc should match.

public override bool Equals (Abc obj)
{
      if (obj.A == A || obj.B == B)
           return true;
      else return false;
}

Can anyone let me know what kind of GetHashCode function would give equal values in such cases.

Because both A & B fields may or may not have same values.

Bulat
  • 720
  • 7
  • 15
  • Hello, I'm not sure if i understand your question: Do you want to compare string A with string B of class Abc? Or do you want to match i.e. two instances of Abc to either have an equal A or B? – Lennart May 10 '19 at 08:31
  • Could be really useful to check out this post: https://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overridden – Lennart May 10 '19 at 08:33
  • I doubt there is a way to produce a GetHashCode that seems logical in this case. – Lasse V. Karlsen May 10 '19 at 08:34
  • Aside: You have a bug in your `Equals` method - it must be `&&`, not `||`. – 500 - Internal Server Error May 10 '19 at 08:37
  • @500-InternalServerError No, that is the exact thing that makes this illogical. He actually wants the `||`. – Lasse V. Karlsen May 10 '19 at 08:40
  • But he is breaking transitivity rules here, which makes this whole situation pretty bad. I see there is an answer here that mentions this now. – Lasse V. Karlsen May 10 '19 at 08:41
  • Well, IMHO, attempting to redefine the semantics of `Equals` will cause nothing but headaches. – 500 - Internal Server Error May 10 '19 at 08:44
  • My question here is { A=John B =Smith} and {A=John B=Doe} this both objects are equal in my coding scenario. Hence I needed similar hashcode function implemented. If any one of the field matches, its a match for me. – prasadkhare May 10 '19 at 09:27

1 Answers1

5

The one and only must-have requirement for implementing GetHashCode is that when two objects are considered equal (i.e. Equals returns true), then their hash codes must match.

In your case, if you have two different objects with x = (A1, B1) and y = (A2, B2), then their hash code must be the same because it must be the same as z = (A1, B2), because x and z are considered equal and so are y and z. Therefore, the only valid implementation of GetHashCode is to always return a constant number, for example 0.

You might wonder because a GetHashCode implementation that simply returns a constant number makes no sense and that is true; the reason is that your Equals also does not make sense. Your biggest problem is that Equals is not transitive. x and z are equal and z and y are, but x and y are not. This is contrary to what you would expect.

Georg
  • 5,626
  • 1
  • 23
  • 44