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 have derived classes:
public class Derived1:AbstractDictionaryObject
{...}
public class Derived2:AbstractDictionaryObject
{...}
In the AbstractDictionaryObject is only one common field: LangId.
I think this is not enough to overload methods (properly).
How can I identify objects?
For one thing you can simplify both your methods:
But at that point it should be fine. If the two derived classes have other fields, they should override
GetHashCodeandEqualsthemselves, first callingbase.Equalsorbase.GetHashCodeand then applying their own logic.Two instances of
Derived1with the sameLangIdwill be equivalent as far asAbstractDictionaryObjectis concerned, and so will two instances ofDerived2– but they will be different from each other as they have different types.If you wanted to give them different hash codes you could change
GetHashCode()to:However, hash codes for different objects don’t have to be different… it just helps in performance. You may want to do this if you know you will have instances of different types with the same
LangId, but otherwise I wouldn’t bother.