Bird
0
0

What will be the output of this C# code?

medium📝 Predict Output Q4 of 15
C Sharp (C#) - Polymorphism and Abstract Classes
What will be the output of this C# code?
class Animal { public virtual string Speak() => "Animal sound"; }
class Dog : Animal { public override string Speak() => "Bark"; }
Animal a = new Dog();
Console.WriteLine(a.Speak());
ACompile error
BAnimal sound
CBark
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand polymorphic call

    Variable 'a' is of type Animal but refers to a Dog object. The Speak method is virtual and overridden in Dog.
  2. Step 2: Determine which Speak method runs

    At runtime, the overridden Dog.Speak() method is called, printing "Bark".
  3. Final Answer:

    Bark -> Option C
  4. Quick Check:

    Virtual method calls overridden version at runtime [OK]
Quick Trick: Virtual methods call overridden version at runtime [OK]
Common Mistakes:
MISTAKES
  • Thinking base class method runs due to variable type
  • Expecting compile or runtime errors
  • Confusing override with new keyword

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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