C# Polymorphism
Polymorphism means 'many forms' — it allows objects of different derived classes to be treated through a common base class or interface, while each behaves according to its specific type.
In C#, polymorphism is commonly achieved using virtual methods in a base class that are overridden in derived classes with the override keyword.
public virtual void Method() { }
public override void Method() { }virtual and override
A base class method marked `virtual` can be replaced in a derived class using `override`. When called through a base class reference, the derived class's version runs.
Why polymorphism matters
Polymorphism lets you write code that works with a general base type, like Animal, while automatically getting the correct specific behavior for Dog, Cat, or any other derived type.
using System;
class Animal {
public virtual void MakeSound() {
Console.WriteLine("Some sound");
}
}
class Dog : Animal {
public override void MakeSound() {
Console.WriteLine("Woof!");
}
}
class Program {
static void Main() {
Animal a = new Dog();
a.MakeSound();
}
}Woof!Even though a is typed as Animal, the overridden Dog version runs because of polymorphism.
using System;
class Shape {
public virtual double Area() { return 0; }
}
class Circle : Shape {
public double Radius;
public Circle(double r) { Radius = r; }
public override double Area() { return Math.PI * Radius * Radius; }
}
class Program {
static void Main() {
Shape s = new Circle(2);
Console.WriteLine(Math.Round(s.Area(), 2));
}
}12.57Calling Area() on a Shape reference runs Circle's overridden calculation.
Key points
- Polymorphism lets different classes be used through a common base type.
- A base class method must be marked virtual to allow overriding.
- The override keyword replaces the base implementation in a derived class.
- The actual method that runs depends on the object's real type, not its reference type.
