Virtual method dispatch mechanism in C Sharp (C#) - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When a program calls a virtual method, it decides at runtime which version to run. This process is called virtual method dispatch.
We want to understand how the time to find and run the right method changes as the program grows.
Analyze the time complexity of calling a virtual method in a class hierarchy.
public class Animal {
public virtual void Speak() {
Console.WriteLine("Animal sound");
}
}
public class Dog : Animal {
public override void Speak() {
Console.WriteLine("Bark");
}
}
Animal pet = new Dog();
pet.Speak();
This code calls a virtual method Speak on an object that is actually a Dog. The program must find the right Speak method to run.
Virtual method dispatch involves looking up the method to call at runtime.
- Primary operation: Accessing the method table (vtable) to find the correct method.
- How many times: Once per virtual method call.
The time to dispatch a virtual method call stays about the same no matter how many classes or methods exist.
| Input Size (number of classes) | Approx. Operations |
|---|---|
| 10 | 1 method lookup |
| 100 | 1 method lookup |
| 1000 | 1 method lookup |
Pattern observation: The lookup time does not grow with the number of classes; it stays constant.
Time Complexity: O(1)
This means the time to find and call the right method stays the same no matter how many classes or methods there are.
[X] Wrong: "Virtual method calls take longer as the number of classes grows because the program searches through all classes."
[OK] Correct: The program uses a direct lookup table, so it finds the method quickly without searching through all classes.
Understanding virtual method dispatch helps you explain how object-oriented programs run efficiently. It shows you know how programs handle flexible behavior without slowing down.
"What if the program used a different method lookup strategy that searched classes one by one? How would the time complexity change?"
Practice
virtual methods let child classes provide their own version of a method. What is the main benefit?Solution
Step 1: Understand virtual method purpose
Virtual methods allow child classes to override a method and provide their own implementation.Step 2: Identify when method is chosen
The actual method called is decided at runtime, based on the object's real type, not the variable's type.Final Answer:
It allows the program to decide at runtime which method version to call. -> Option DQuick Check:
Virtual method dispatch = runtime method choice [OK]
- Thinking method is fixed at compile time
- Confusing virtual with static methods
- Assuming base method always runs
Solution
Step 1: Recall virtual method syntax
The keywordvirtualcomes after the access modifier and before the return type and method name.Step 2: Check each option
public virtual void Display() { } matches correct syntax:public virtual void Display() { }. Options B and C have wrong order, D usesoverridewhich is for overriding, not declaring virtual.Final Answer:
public virtual void Display() { } -> Option CQuick Check:
virtual keyword after access modifier [OK]
- Placing virtual after method name
- Using override instead of virtual to declare
- Wrong keyword order
class Base {
public virtual string GetName() => "Base";
}
class Derived : Base {
public override string GetName() => "Derived";
}
Base obj = new Derived();
Console.WriteLine(obj.GetName());What will be the output?
Solution
Step 1: Identify method overriding
TheDerivedclass overrides the virtual methodGetNamefromBase.Step 2: Understand virtual dispatch
The variableobjis of typeBasebut holds aDerivedobject. Virtual dispatch calls theDerivedversion at runtime.Final Answer:
Derived -> Option BQuick Check:
Virtual method calls child's override [OK]
- Assuming base method runs due to variable type
- Confusing compile-time and runtime binding
- Expecting errors from override
class Animal {
public virtual void Speak() {
Console.WriteLine("Animal speaks");
}
}
class Dog : Animal {
public void Speak() {
Console.WriteLine("Dog barks");
}
}
Animal a = new Dog();
a.Speak();Solution
Step 1: Check method overriding rules
To override a virtual method, the child method must useoverridekeyword.Step 2: Analyze given code
Dog'sSpeakmethod lacksoverride, so it hides base method instead of overriding. Virtual dispatch calls base method.Final Answer:
Dog's Speak method should be marked override to override base virtual method. -> Option AQuick Check:
Override keyword needed to override virtual method [OK]
- Forgetting override keyword in child method
- Assuming method hides base automatically
- Confusing virtual and override keywords
Shape with a virtual method Draw(). Two derived classes Circle and Square override Draw(). You want to write a method that takes a list of Shape objects and calls Draw() on each, ensuring the correct derived method runs.Which approach correctly uses virtual method dispatch to achieve this?
Solution
Step 1: Understand virtual method usage
DeclaringDraw()as virtual in base allows derived classes to override it.Step 2: Use polymorphism in list iteration
CallingDraw()on eachShapereference triggers virtual dispatch, running the correct derived method.Final Answer:
Declare Draw() as virtual in Shape, override in derived, call Draw() on each Shape reference. -> Option AQuick Check:
Virtual + override + call on base type = correct method run [OK]
- Using static methods which don't support polymorphism
- Manually casting instead of relying on virtual dispatch
- Calling base method explicitly ignoring overrides
