Loading lessons...
Polymorphism
C# Polymorphism
Polymorphism means "many forms". In C#, derived classes can override a base class method so the same method call behaves differently per object.
The virtual and override keywords
virtual- the base method can be overridden.override- the derived method replaces the base version.
class Animal // base class
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Pig : Animal
{
public override void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
class Dog : Animal
{
public override void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
Calling polymorphic methods
Animal myAnimal = new Animal();
Animal myPig = new Pig();
Animal myDog = new Dog();
myAnimal.animalSound(); // The animal makes a sound
myPig.animalSound(); // The pig says: wee wee
myDog.animalSound(); // The dog says: bow wow
Even though myDog is declared as Animal, it calls the Dog version.
Why polymorphism matters
One method name (animalSound) works for every animal. New animal classes are added without touching the code that calls animalSound - the right version is chosen automatically at runtime.
Overriding vs overloading (recap)
- Overriding: derived class replaces a
virtualbase method (same signature). - Overloading: same class, multiple methods with different signatures.
TL;DR
- Polymorphism = same method call, different behavior.
virtualin base,overridein derived.- The right version runs even through a base-typed reference.
- Polymorphism + inheritance make code extensible.