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.
The output of your program is the
Animalclass implementation ofFoosince the type of the reference isAnimaland notCat.If the reference was of type
Cat, the output would be"Cat::Foo()".The
Foomethod of theCatclass is hiding theFoomethod of theAnimalclass 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
newmodifier. This will tell the compiler that the hiding is deliberate, and will suppress the warning.