Skip to content
Sharp

Object-oriented programming · interview question

What does this program print?

What does this code output?Medium
C#
Animal a = new Dog();
Console.WriteLine($"{a.Speak()} {a.Name()}");

class Animal
{
    public virtual string Speak() => "...";
    public string Name() => "Animal";
}

class Dog : Animal
{
    public override string Speak() => "Woof";
    public new string Name() => "Dog";
}
Choose one answer
Answer and explanation

Correct answer

A. Woof Animal

Why

override participates in virtual dispatch: the runtime type decides, so Speak() returns "Woof". new merely hides the base member; the compile-time type of the reference (Animal) decides, so Name() returns "Animal".

Test yourself on Object-oriented programming

A free test with instant, explained results. No account needed.

Start free test
All Object-oriented programming questions →