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 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
==
did in fact call yourEquals
method, then it would cause a stack overflow as it uses the==
operator on the object... – Guffa