Bird
Raised Fist0

What will be the output of the following code?

medium📝 Predict Output Q4 of Q15
C Sharp (C#) - Polymorphism and Abstract Classes
What will be the output of the following code?
class Base {
    public virtual string GetMessage() => "Base";
}
class Derived : Base {
    public override string GetMessage() => "Derived";
}
class Program {
    static void Main() {
        Base obj = new Derived();
        System.Console.WriteLine(obj.GetMessage());
    }
}
ABase
BRuntime exception
CDerived
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze object type and method call

    The variable obj is of type Base but references a Derived object.
  2. Step 2: Understand virtual method dispatch

    Calling the virtual method GetMessage on obj invokes the Derived override at runtime.
  3. Final Answer:

    Derived -> Option C
  4. Quick Check:

    Virtual dispatch calls derived method = Derived [OK]
Quick Trick: Virtual calls use actual object type at runtime [OK]
Common Mistakes:
MISTAKES
  • Expecting base method output
  • Confusing compile-time type with runtime type
  • Thinking virtual methods cause errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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