Question

Say I have one class, ClassB, that extends another class, ClassA, by adding another property not in ClassA. Would the following equals method work?

public bool Equals(ClassB other)
{
    return this.ExtraProp == other.ExtraProp && base.Equals(ClassB);
}

Why should I be allowed to pass a ClassB object to the equals method of ClassA (only takes ClassA objects)? Is this just how inheritance works?

Was it helpful?

Solution

Because a ClassB object is a ClassA object. You can always, anywhere, treat a ClassB object as if it were a ClassA object. This is the essence of polymorphism.

As for whether it would actually return the proper result, that is going to depend on your implementation of ClassA. Certain implementation wouldn't work as this code is expecting them to, but other implementations would.

Let's use a concrete example here. Let's say that this is the definition of ClassA:

public class ClassA
{
    public int first;
    public int second;
    public bool Equals(ClassA other)
    {
        if (other == null) return false;
        return first == other.first &&
            second == other.second;
    }
}

Now let's say we have these objects:

ClassA a = new ClassA() { first = 1, second = 2 };
ClassB b = new ClassB() { first = 1, second = 2, third = 3 };

Here a.Equals(b) will be true. It has both of the properties that are checked for, so it considers them equal. Do you want these objects to be considered equal?

Another implementation would be to do this:

public bool Equals(ClassA other)
{
    if (other == null) return false;
    if (other.GetType() != typeof(ClassA)) return false;
    return first == other.first &&
        second == other.second;
}

Here we're explicitly checking (granted, at runtime, not at compile time) to be sure that the other instance isn't of a more derived type. In this case a.Equals(b) would be false. You can implement whichever semantics you prefer.

OTHER TIPS

Employee inherits from Human.

Employee has more properties than just a Human, but it is still a Human.

If you implement a Human.Equals() you can pass in an Employee because deepdown at heart Employees are still Humans.... but you cannot treat Humans like Employees, because not all Humans have the Earnings Property

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top