C# · Chapter 35 of 46

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.

Syntax
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.

Example 1 (csharp)
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();
  }
}
Output
Woof!

Even though a is typed as Animal, the overridden Dog version runs because of polymorphism.

Example 2 (csharp)
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));
  }
}
Output
12.57

Calling 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.
💡 Note: Polymorphism makes code more flexible and extensible, since new derived classes can be added without changing code that uses the base type.

📝 Quick Quiz

1. What keyword allows a base class method to be overridden?

2. What keyword replaces a base method's implementation?

3. In the Animal/Dog example, which MakeSound() runs when calling it through an Animal reference pointing to a Dog object?