virtual/override enables runtime polymorphism through base class references—calls dispatch to the actual derived type. Without virtual, methods are hidden, not overridden—unlike polymorphic dispatch in Java where instance methods are virtual by default.
Override example
class Animal {
public virtual void Speak() => Console.WriteLine("...");
}
class Dog : Animal {
public override void Speak() => Console.WriteLine("woof");
}
Animal pet = new Dog();
pet.Speak(); // woof
Important interview questions and answers
- Q: virtual vs override?
A:virtualallows derived override;overridereplaces base implementation for polymorphic calls. - Q: new keyword hiding?
A:newhides a base member without polymorphism—calls through base type still use base implementation.
Self-check
- What keyword enables polymorphic dispatch?
- What happens if base method is not virtual?
Tip: Mark base methods virtual and derived methods override—without virtual, calls resolve at compile time to the base type.
Interview prep
- virtual vs override?
virtualon the base enables overriding;overrideon derived replaces behavior—calls through base references dispatch at runtime.- new keyword hiding?
newhides a base member without overriding—polymorphism through base references still calls the base version.