Bird
Raised Fist0

What will be the output of this C# code?

medium📝 Predict Output Q4 of Q15
C Sharp (C#) - Inheritance
What will be the output of this C# code?
class Vehicle {
  public virtual string GetType() {
    return "Vehicle";
  }
}
class Car : Vehicle {
  public override string GetType() {
    return "Car";
  }
}
class Program {
  static void Main() {
    Vehicle v = new Car();
    System.Console.WriteLine(v.GetType());
  }
}
AVehicle
BCompilation error
CCar
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Understand virtual and override methods

    The base class method is marked virtual, and the derived class overrides it. This enables polymorphism.
  2. Step 2: Analyze object type and method call

    The variable is of type Vehicle but holds a Car object. The overridden method in Car is called at runtime.
  3. Final Answer:

    Car -> Option C
  4. Quick Check:

    Virtual override calls derived method = Car [OK]
Quick Trick: Virtual methods call derived override at runtime [OK]
Common Mistakes:
MISTAKES
  • Thinking base method runs due to variable type
  • Expecting compilation or runtime error
  • Ignoring virtual/override behavior

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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