Glossary / Virtual dispatch
Virtual dispatch
Virtual dispatch selects an overridden instance member implementation based on an object's runtime type rather than only the compile-time reference type. C# uses virtual/override for class methods and properties, and interface dispatch for interface members; nonvirtual members use compile-time member selection.
Dispatch and hiding
Base item = new Derived();
item.VirtualMethod(); // Derived implementation if overridden
item.NonVirtualMethod(); // Base implementation selected by compile-time type
A base member must be marked virtual, abstract, or already override to be overridden. override preserves the virtual slot; new hides a member and does not replace virtual dispatch. Static members are not virtual. Sealed overrides can stop further overriding. Calls from constructors can dispatch to derived overrides before derived fields initialize, which is a common hazard.
The runtime may devirtualize calls when it can prove the concrete type, so virtual syntax does not always mean a runtime dispatch cost in optimized code. Design should prioritize behavioral correctness; measure performance if dispatch is suspected.
Interview questions
- What determines a virtual call target? Runtime type of the receiver.
- What does
newdo? Hides a member for compile-time lookup; it does not override a virtual slot. - Can static methods be virtual? No.
- Why avoid virtual calls in constructors? Derived implementations can run before derived initialization.
- What is devirtualization? Runtime/JIT optimization replacing a virtual call when target is provably known.