C# Polymorphism
Polymorphism means "many forms". In C#, it lets a single method behave differently depending on which class is actually running it. This makes your code flexible and easy to extend.
What Is Polymorphism?
Polymorphism usually works together with inheritance. It allows many derived classes to share the same method name from a base class, while each class provides its own version of that method. When you call the method, C# runs the correct version for the object you actually have.
A common example is a group of animals. Every animal can make a sound, but a cat and a dog make different sounds. With polymorphism you can loop through a list of animals and simply call MakeSound on each one, and every animal responds in its own way.
The virtual and override Keywords
To let a derived class replace a base class method, mark the base method with the virtual keyword. Then in the derived class, mark the new version with the override keyword. Without these keywords, the base version would always run.
Overriding a virtual method
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("The animal makes a sound.");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("The dog says: woof woof");
}
}
class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("The cat says: meow");
}
}Polymorphism in Action
The real power appears when you store different objects in a variable of the base type. Even though the variable is typed as Animal, C# still calls the correct overridden method at run time. This is called run-time polymorphism.
One loop, many behaviours
Animal[] animals = { new Animal(), new Dog(), new Cat() };
foreach (Animal a in animals)
{
a.MakeSound();
}
// Output:
// The animal makes a sound.
// The dog says: woof woof
// The cat says: meowPolymorphism lets you write general code that works with the base type, while each specific class supplies its own details. Adding a new animal later does not require changing the loop at all.
Exercise: C# Polymorphism
What are the two main categories of polymorphism in C#?