C # GetHashCode / Equals override not called

I ran into a problem with GetHashCode and Equals, which I redefined for the class. I use the == operator to make sure they are both equal, and I would expect this to call both GetHashCode and Equals if their hash code is the same, to check if they are really equal.

But, to my surprise, neither the challenge nor the result of the equality test is false (although this should be true).

Override Code:

public class User : ActiveRecordBase<User> [...] public override int GetHashCode() { return Id; } public override bool Equals(object obj) { User user = (User)obj; if (user == null) { return false; } return user.Id == Id; } } 

Equality Check:

  if (x == y) // x and y are both of the same User class // I'd expect this test to call both GetHashCode and Equals 
+7
c # operator-overloading
source share
2 answers

The == operator is completely separate from .GetHashCode() or .Equals() .

You might be interested in Microsoft Recommendations for Overloading Equals () and Operator == .

Short version: Use .Equals() to implement equality comparisons. Use the == operator for identity mappings, or if you are creating an immutable type (where each equal instance can be considered virtually identical). In addition, .Equals() is a virtual method and can be overridden by subclasses, but the == operator depends on the type of compilation time of the expression in which it is used.

Finally, to be consistent, implement .GetHashCode() anytime you implement .Equals() . Overload operator != When operator overload == .

+11
source share

it is possible to add another method to your User class.

  public virtual bool Equals(User other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return other.Id == Id; } 
+1
source share

All Articles