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.
Jon skeet
source share