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.

8
  • 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? Commented May 10, 2019 at 8:31
  • Could be really useful to check out this post: stackoverflow.com/questions/371328/… Commented May 10, 2019 at 8:33
  • I doubt there is a way to produce a GetHashCode that seems logical in this case. Commented May 10, 2019 at 8:34
  • Aside: You have a bug in your Equals method - it must be &&, not ||. Commented May 10, 2019 at 8:37
  • @500-InternalServerError No, that is the exact thing that makes this illogical. He actually wants the ||. Commented May 10, 2019 at 8:40

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.