Bird
0
0

What will this C# program print?

medium📝 Predict Output Q5 of 15
C Sharp (C#) - Polymorphism and Abstract Classes
What will this C# program print?
class A { public virtual string Msg() => "A"; } class B : A { public override string Msg() => "B"; } class C : B { public new string Msg() => "C"; } class Program { static void Main() { A obj = new C(); Console.WriteLine(obj.Msg()); } }
AB
BCompilation error
CC
DA
Step-by-Step Solution
Solution:
  1. Step 1: Analyze method declarations

    Class C defines Msg() with 'new', hiding B's override. Variable obj is type A, holding C instance.
  2. Step 2: Determine method called at runtime

    Since Msg() is virtual in A and overridden in B, but C's method hides instead of overrides, the override in B is called.
  3. Final Answer:

    B -> Option A
  4. Quick Check:

    New keyword hides, override wins in polymorphism [OK]
Quick Trick: 'new' hides method, doesn't override virtual method [OK]
Common Mistakes:
MISTAKES
  • Thinking 'new' overrides virtual methods
  • Expecting C's Msg() to run via base type
  • Confusing method hiding with overriding

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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