Warning: "Object is overridden. Object is not overridden by Equals(object o). GetHashCode()"

.net c# entity-framework


I overrode the Equals() of my class to compare ID values of type Guid.

Then Visual Studio warned:

... overrides Object.Equals(object o) but does not override Object.GetHashCode()

So I then also overrode its GetHashCode() like this:

public partial class SomeClass
    public override bool Equals(Object obj)
        //Check for null and compare run-time types.
        if (obj == null || this.GetType() != obj.GetType()) return false;

        return this.Id == ((SomeClass)obj).Id;

    public override int GetHashCode()
        return this.Id.GetHashCode();

It seems to work. Have I done this correctly? Remember Id is of type Guid. Does it matter that my class is an Entity Framework object?

6/24/2011 9:19:49 PM

Popular Answer

As others have said, the use of Reflection in Equals seems dodgy. Leaving that aside, let's concentrate on GetHashCode.

The primary rule for GetHashCode that you must not violate is if two objects are equal then they must both have the same hash code. Or, an equivalent way of saying that is if two objects have different hash codes then they must be unequal. Your implementation looks good there.

You are free to violate the converse. That is, if two objects have the same hash code then they are permitted to be equal or unequal, as you see fit.

I am assuming that "Id" is an immutable property. If "Id" can change over the lifetime of the object then you can have problems when putting the object in a hash table. Consider ensuring that only immutable properties are used in computing equality and hash code.

Your implementation looks good but the fact that you are asking the question indicates that you might not have a solid grasp of all the subtle factors that go into building an implementation of GetHashCode. A good place to start is my article on the subject:


5/6/2014 4:21:29 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow