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

.net c# entity-framework


To compare ID values of type Guid, I overrode the Equals() function in my class.

Then Visual Studio sent the following advice:

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

I then modified its GetHashCode() in the following manner:

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 appears to function. Am I doing this right? Keep in mind that Id is of type Guid. The fact that my class is an Entity Framework object is it important?

6/24/2011 9:19:49 PM

Popular Answer

The usage of reflection in Equals appears questionable, as others have stated. Let's ignore it and focus on GetHashCode.

The main GetHashCode rule that you can't break is Two items must have the same hash code in order for them to be equal.. Or, Two items must be unequal if their hash codes disagree. would be an equal method to state it. Your execution there looks fantastic.

You may go against the converse at will. In other words, if two items have the same hash code, you may decide whether they should be equal or unequal.

I'm assuming that the attribute "Id" is unchangeable. When placing an item in a hash table, issues may arise if "Id" is susceptible to change during the course of the object's existence. Consider making sure that the hash code and equality calculations only employ immutable attributes.

Although your implementation seems to be excellent, the fact that you are asking the question suggests that you may not fully understand all the complex elements involved in creating an implementation of GetHashCode. My piece on the matter is a wonderful place to start:


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