Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
C Sharp (C#) - Inheritance
What will be the output of this code?
class Base {
  public virtual string Greet() => "Hello from Base";
}
class Derived : Base {
  public override string Greet() => "Hello from Derived";
}
class Program {
  static void Main() {
    Base obj = new Derived();
    System.Console.WriteLine(obj.Greet());
  }
}
AHello from Derived
BRuntime error
CCompilation error
DHello from Base
Step-by-Step Solution
Solution:
  1. Step 1: Understand virtual and override behavior

    The variable is of type Base but holds a Derived object. The overridden method in Derived is called at runtime.
  2. Step 2: Predict output

    Because Greet is virtual and overridden, the Derived version runs, printing "Hello from Derived".
  3. Final Answer:

    Hello from Derived -> Option A
  4. Quick Check:

    Virtual override calls derived method = Hello from Derived [OK]
Quick Trick: Virtual methods call derived override even if base type used [OK]
Common Mistakes:
MISTAKES
  • Expecting base method output due to variable type
  • Thinking code causes compile or runtime error
  • Ignoring virtual method dispatch

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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