LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 2518 min read

Polymorphism

Learn method overriding, virtual and override keywords, and runtime polymorphism in C#.

What is Polymorphism?

Polymorphism means "many forms" — it lets objects of different derived classes be treated through a common base type, while each still executes its own specific behavior.

virtual and override

A base class marks a method `virtual` to allow derived classes to replace it using `override`.

class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Some generic animal sound");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Woof!");
}
}
class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Meow!");
}
}

Polymorphism in Action

List<Animal> animals = new List<Animal> { new Dog(), new Cat() };
foreach (Animal animal in animals)
{
animal.MakeSound(); // calls the correct overridden version for each object
}
Output

Click Run to see what this code prints.

Why This is Powerful

The loop only knows about `Animal`, but each object still runs its own specific `MakeSound()` — this is the essence of polymorphism, and it's what lets you write flexible, extensible code.

FAQs

A derived class can still hide it using the `new` keyword, but that's "method hiding", not true polymorphic overriding — the base type reference would call the base version instead.

Summary

  • Polymorphism lets different objects respond to the same call in their own way.
  • `virtual` on the base method allows `override` in derived classes.
  • Collections of a base type can hold mixed derived objects, each behaving correctly.
Next Lesson →

Abstract Classes