Konrad Viltersten Konrad Viltersten - 3 months ago 18
C# Question

Do I have to implement GetHashCode() to follow best practice?

In my class I have the following override.

public override bool Equals(object input)
{
Occasion comparee = input as Occasion;
return comparee != null && comparee.Id == Id;
}


It's being used in the GUI for determining of a combox pre-selected value and it works perfectly. However, R# nags and suggests that, if I have overriden Equals(object), then I also should override GetHashCode(). When I add the following code, it nags that the code is calling the base method.

public override int GetHashCode()
{
return base.GetHashCode();
}


I have to return something, so basically it wants me to implement a dummy method returning an arbitrary integer (it's not being used anywhere in the code as far I can tell because I get the same behavior regardless of whether I have it commented out or not.

Since best practice is to omit the code that isn't needed, I'm confused on what the appropriate design would be.

Answer

The MSDN page for GetHashCode states that

If you override the GetHashCode method, you should also override Equals, and vice versa. If your overridden Equals method returns true when two objects are tested for equality, your overridden GetHashCode method must return the same value for the two objects.

If you are overriding the equals so that it returns true when the object ids are equal, you must define your GetHashCode method to return the same hash code when given the same id.

The hashcode is used for insertion and lookup in collections - so it's unlikely to be used directly by any code you write, but it will be used by other .NET code. But if you don't implement it correctly you may find performance issues or worse when dealing with collections of your object. For example, if you get it wrong or don't implement it then you might not be able to determine whether an instance of your class is in the collection or not, or you won't be able to retrieve the instance you you put in.

In your case the method is simply:

public override int GetHashCode()
{
    return Id.GetHashCode();
}

as you are just comparing the id's in the Equals method.