C# GetHashCode/Equals override not called
I'm facing a problem with GetHashCode and Equals which I have overridden for a class. I am using the operator == to verify if both are equal and I'd expect this would be calling both GetHashCode and Equals if their hash code are the same in order to validate they are indeed equal.
But to my surprise, neither get called and the result of the equality test is false (while it should in fact be true).
Override code:
public class User : ActiveRecordBase<User>
[...]
public override in开发者_开发百科t 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
Operator ==
is completely separate from either .GetHashCode()
or .Equals()
.
You might be interested in the Microsoft Guidelines for Overloading Equals() and Operator ==.
The short version is: Use .Equals()
to implement equality comparisons. Use operator ==
for identity comparisons, or if you are creating an immutable type (where every equal instance can be considered to be effectively identical). Also, .Equals()
is a virtual method and can be overridden by subclasses, but operator ==
depends on the compile-time type of the expression where it is used.
Finally, to be consistent, implement .GetHashCode()
any time you implement .Equals()
. Overload operator !=
any time you overload operator ==
.
perhaps adding one more method in 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;
}
精彩评论