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 Base { public virtual string GetName() => "Base"; } class Derived : Base { public override string GetName() => "Derived"; } class Program { static void Main() { Base obj = new Derived(); Console.WriteLine(obj.GetName()); } }
ACompilation error
BBase
CDerived
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand object type and method call

    Variable obj is of type Base but holds a Derived object. The method GetName is virtual and overridden in Derived.
  2. Step 2: Determine which method runs at runtime

    Because of runtime polymorphism, the overridden method in Derived is called, printing "Derived".
  3. Final Answer:

    Derived -> Option C
  4. Quick Check:

    Virtual method call = Derived method runs [OK]
Quick Trick: Virtual method calls use actual object type at runtime [OK]
Common Mistakes:
MISTAKES
  • Assuming method from variable type runs
  • Expecting compile-time method binding
  • Confusing compilation and runtime errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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