Search code examples
c#oopmember-hiding

Method erasure: why is it said that the the derived class method hides the base class, but it works the other way around?


class Animal
{
    public void Foo() { Console.WriteLine("Animal::Foo()"); }
}

class Cat : Animal
{
    public void Foo() { Console.WriteLine("Cat::Foo()"); }
}

class Test
{
    static void Main(string[] args)
    {
        Animal a;

        a = new Cat();
        a.Foo();  // output --> "Animal::Foo()"
    }
}

The compiler warning says:

Cat.Foo hides the inherited member

However the output actually is from the base class. So to me it seems the other way around, the one I called is hidden by the one in the base class.


Solution

  • The output of your program is the Animal class implementation of Foo since the type of the reference is Animal and not Cat.

    If the reference was of type Cat, the output would be "Cat::Foo()".

    The Foo method of the Cat class is hiding the Foo method of the Animal class because base classes can not and should not be aware of their derived classes, while derived classes are and must be aware of their base classes.

    To deliberately hide a member of the base class, use the new modifier. This will tell the compiler that the hiding is deliberate, and will suppress the warning.