virtual, override and new: Method Hiding Demo
csharpC# and .NETbeginnerinterview-prep
A small program that shows why override is polymorphism and new is only hiding: the same object gives different answers through different variable types.
Animal animal = new Dog(); // the variable's type is Animal, the object is a Dog
Console.WriteLine(animal.Speak()); // Woof virtual + override: the object's run-time type decides
Console.WriteLine(animal.Name()); // Animal new only hides: the variable's compile-time type decides
Dog dog = new Dog();
Console.WriteLine(dog.Speak()); // Woof
Console.WriteLine(dog.Name()); // Dog
public class Animal
{
public virtual string Speak() => "...";
public string Name() => "Animal";
}
public class Dog : Animal
{
public override string Speak() => "Woof";
public new string Name() => "Dog"; // hides Animal.Name(); remove "new" to see the compiler warning
}