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#)
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.