Bird
0
0

Given this code, what will be the output?

hard🚀 Application Q8 of 15
C Sharp (C#) - Inheritance
Given this code, what will be the output?
class Animal {
  public virtual string Sound() => "Some sound";
}
class Dog : Animal {
  public override string Sound() => "Bark";
}
class Cat : Animal {
  public override string Sound() => "Meow";
}
class Program {
  static void Main() {
    Animal[] pets = { new Dog(), new Cat(), new Animal() };
    foreach (var pet in pets) {
      System.Console.WriteLine(pet.Sound());
    }
  }
}
ASome sound Some sound Some sound
BBark Meow Some sound
CBark Some sound Meow
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand polymorphism with virtual methods

    Each object calls its own overridden Sound() method at runtime.
  2. Step 2: Predict output for each array element

    Dog outputs "Bark", Cat outputs "Meow", Animal outputs "Some sound".
  3. Final Answer:

    Bark Meow Some sound -> Option B
  4. Quick Check:

    Virtual override calls correct method per object type [OK]
Quick Trick: Virtual methods call correct override per object in array [OK]
Common Mistakes:
MISTAKES
  • Expecting base method output for all
  • Confusing compile error due to array of base type
  • Ignoring override dispatch

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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