8
votes

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
2
If the == did in fact call your Equals method, then it would cause a stack overflow as it uses the == operator on the object...Guffa
There's nothing in the code you show that would indicate a need to call GetHashCode(). That's only called if you use your object as the key of a collection.RenniePet

2 Answers

13
votes

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 ==.

1
votes

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;
    }