Bird
0
0

Given a base class Instrument with a virtual method Play() and derived classes Guitar and Piano overriding Play(), which code snippet correctly demonstrates runtime polymorphism when calling Play() on a list of instruments?

hard🚀 Application Q8 of 15
C Sharp (C#) - Polymorphism and Abstract Classes
Given a base class Instrument with a virtual method Play() and derived classes Guitar and Piano overriding Play(), which code snippet correctly demonstrates runtime polymorphism when calling Play() on a list of instruments?
AList<Instrument> instruments = new List<Instrument> { new Guitar(), new Piano() }; foreach (var inst in instruments) { inst.Play(); }
BList<Guitar> instruments = new List<Guitar> { new Guitar(), new Piano() }; foreach (var inst in instruments) { inst.Play(); }
CList<Instrument> instruments = new List<Instrument> { new Guitar(), new Piano() }; foreach (Guitar inst in instruments) { inst.Play(); }
DList<Instrument> instruments = new List<Instrument> { new Guitar(), new Piano() }; foreach (var inst in instruments) { Instrument.Play(); }
Step-by-Step Solution
Solution:
  1. Step 1: Understand polymorphic collection

    To use runtime polymorphism, store derived objects in a base class collection.
  2. Step 2: Analyze options

    List<Instrument> instruments = new List<Instrument> { new Guitar(), new Piano() }; foreach (var inst in instruments) { inst.Play(); } correctly uses a List<Instrument> holding Guitar and Piano objects and calls Play() polymorphically.
  3. Step 3: Identify errors in other options

    List<Guitar> instruments = new List<Guitar> { new Guitar(), new Piano() }; foreach (var inst in instruments) { inst.Play(); } uses List<Guitar> but adds Piano (invalid). List<Instrument> instruments = new List<Instrument> { new Guitar(), new Piano() }; foreach (Guitar inst in instruments) { inst.Play(); } casts to Guitar in foreach, causing invalid cast. List<Instrument> instruments = new List<Instrument> { new Guitar(), new Piano() }; foreach (var inst in instruments) { Instrument.Play(); } calls Instrument.Play() statically, not polymorphically.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Use base class list and virtual methods [OK]
Quick Trick: Use base class list and virtual methods [OK]
Common Mistakes:
MISTAKES
  • Using derived class list for multiple derived types
  • Incorrect casting in foreach
  • Calling base class method statically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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