Polymorphism & dynamic dispatch
Understand polymorphism: call virtual members through a base reference, use base-typed collections, avoid method hiding, and cast safely when needed.
Polymorphism overview
Goal: Use one base type and let derived types customize behavior.
- Base reference, derived object
- virtual + override → dynamic dispatch
- Base-typed collections
- Avoid new method hiding
Dynamic dispatch basics
Calling a virtual method uses the object’s runtime type, not the variable’s compile-time type.
using System;
public class Animal
{
public virtual string Speak() { return "???"; }
}
public class Cat : Animal
{
public override string Speak() { return "Meow"; }
}
public class Dog : Animal
{
public override string Speak() { return "Woof"; }
}
public class Program
{
public static void Main(string[] args)
{
Animal a1 = new Cat(); // base reference
Animal a2 = new Dog();
Console.WriteLine(a1.Speak()); // Meow
Console.WriteLine(a2.Speak()); // Woof
}
}
All lessons in this course
- virtual/override/sealed; abstract classes
- Interfaces (intro) & multiple interface implementation
- Polymorphism & dynamic dispatch