I'm looking for the best way to implement IEquatable<T>
in such a way that type checking is implicit. If I call Equals
in a child class, I want to ensure that the type I'm comparing to is the same. See the stripped down example below.
Two Child1
objects should be considered equal if their ID is the same. In this example, calling child1.Equals(child2)
will return true if their ID is the same, which is not the intended behavior. I would basically like to force instances of Child1
to use an overload of Equals
that requires a Child1
parameter, not simply a parameter that derives from the same base class as Child1
.
I'm starting to think that I'm approaching this in the wrong way. Perhaps I should just leave the implementation of Equals
in the base class, and ensure that this.GetType() == other.GetType()
?
public abstract class BaseClass : IEquatable<BaseClass>
{
public int ID { get; set; }
public bool Equals(BaseClass other)
{
return
other != null &&
other.ID == this.ID;
}
}
public sealed class Child1 : BaseClass
{
string Child1Prop { get; set; }
public bool Equals(Child1 other)
{
return base.Equals(other as BaseClass);
}
}
public sealed class Child2 : BaseClass
{
string Child2Prop { get; set; }
public bool Equals(Child2 other)
{
return base.Equals(other as BaseClass);
}
}