Virtual method dispatch lets a program decide which version of a method to run when you have many classes connected by inheritance. It helps the program pick the right behavior at runtime.
Virtual method dispatch mechanism in C Sharp (C#)
Start learning this pattern below
Jump into concepts and practice - no test required
class BaseClass { public virtual void Show() { Console.WriteLine("Base class method"); } } class DerivedClass : BaseClass { public override void Show() { Console.WriteLine("Derived class method"); } }
virtual keyword marks a method that can be changed in child classes.
override keyword tells the program this method replaces the base version.
class Animal { public virtual void Speak() { Console.WriteLine("Animal sound"); } } class Dog : Animal { public override void Speak() { Console.WriteLine("Bark"); } }
class Shape { public virtual void Draw() { Console.WriteLine("Drawing shape"); } } class Circle : Shape { public override void Draw() { Console.WriteLine("Drawing circle"); } } class Square : Shape { public override void Draw() { Console.WriteLine("Drawing square"); } }
This program shows virtual method dispatch. The variable type is Animal, but the method called depends on the actual object type (Animal, Dog, or Cat).
using System; class Animal { public virtual void Speak() { Console.WriteLine("Animal sound"); } } class Dog : Animal { public override void Speak() { Console.WriteLine("Bark"); } } class Cat : Animal { public override void Speak() { Console.WriteLine("Meow"); } } class Program { static void Main() { Animal myAnimal = new Animal(); Animal myDog = new Dog(); Animal myCat = new Cat(); myAnimal.Speak(); myDog.Speak(); myCat.Speak(); } }
If you forget virtual in the base class, the method cannot be overridden properly.
Virtual method dispatch happens at runtime, so the program picks the right method based on the actual object.
You can call the base method inside the override using base.MethodName() if needed.
Virtual methods let child classes provide their own version of a method.
The program decides which method to run when it runs, not when it compiles.
This helps write flexible and reusable code using inheritance and polymorphism.
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
