Bird
0
0

What is the output of this C# code?

medium📝 Predict Output Q13 of 15
C Sharp (C#) - Polymorphism and Abstract Classes
What is the output of this C# code?
class Animal {
  public virtual string Speak() => "Animal sound";
}
class Dog : Animal {
  public override string Speak() => "Bark";
}
class Cat : Animal {
  public override string Speak() => "Meow";
}

Animal a = new Dog();
Console.WriteLine(a.Speak());
AAnimal sound
BBark
CMeow
DCompile error
Step-by-Step Solution
Solution:
  1. Step 1: Identify object type and method called

    Variable a is of type Animal but references a Dog object.
  2. Step 2: Apply runtime polymorphism

    Since Speak is virtual and overridden in Dog, the Dog version runs, printing "Bark".
  3. Final Answer:

    Bark -> Option B
  4. Quick Check:

    Base ref calls Dog's Speak() = Bark [OK]
Quick Trick: Base ref calls derived override method at runtime [OK]
Common Mistakes:
MISTAKES
  • Expecting base class method output
  • Confusing object type with reference type
  • Thinking compile error due to override

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes