Override Equals and GetHashCode in a Single Field Class

I have a class:

public abstract class AbstractDictionaryObject { public virtual int LangId { get; set; } public override bool Equals(object obj) { if (obj == null || obj.GetType() != GetType()) { return false; } AbstractDictionaryObject other = (AbstractDictionaryObject)obj; if (other.LangId != LangId) { return false; } return true; } public override int GetHashCode() { int hashCode = 0; hashCode = 19 * hashCode + LangId.GetHashCode(); return hashCode; } 

And I got the classes:

 public class Derived1:AbstractDictionaryObject {...} public class Derived2:AbstractDictionaryObject {...} 

There is only one common field in AbstractDictionaryObject : LangId .
I think this is not enough to overload the methods (correctly).
How can I identify objects?

+2
source share
1 answer

On the one hand, you can simplify both methods:

  public override bool Equals(object obj) { if (obj == null || obj.GetType() != GetType()) { return false; } AbstractDictionaryObject other = (AbstractDictionaryObject)obj; return other.LangId == LangId; } public override int GetHashCode() { return LangId; } 

But at that moment everything should be fine. If two derived classes have other fields, they must override GetHashCode and Equals themselves, first calling base.Equals or base.GetHashCode , and then applying their own logic.

Two instances of Derived1 with the same LangId will be equivalent to AbstractDictionaryObject , as well as two instances of Derived2 - but they will be different from each other because they are of different types.

If you want to give them different hash codes, you can change GetHashCode() to:

  public override int GetHashCode() { int hash = 17; hash = hash * 31 + GetType().GetHashCode(); hash = hash * 31 + LangId; return hash; } 

However, the hash codes for different objects should not be different ... it just helps in performance. You can do this if you know that you will have instances of different types with the same LangId , but otherwise I would not bother.

+6
source

All Articles