← Back to C# Course | Chapter 7: Inheritance | Lesson 6 of 6

Polymorphism

In this page:

  1. Polymorphism

Polymorphism

Polymorphism lets you treat objects of different derived types uniformly through a shared base type or interface, while each still runs its own overridden behavior. A single List<Shape> can hold circles, squares, and triangles, and calling Area() on each invokes the right implementation automatically. This is what makes overriding genuinely useful rather than just syntax.

Note: Polymorphism is why you can write one loop that works correctly no matter which subclass each object actually is.

Example: Polymorphism

markup
using System;
using System.Collections.Generic;

class Shape
{
    public virtual double Area() => 0;
}

class Circle : Shape
{
    public double Radius;
    public Circle(double r) { Radius = r; }
    public override double Area() => Math.PI * Radius * Radius;
}

class Square : Shape
{
    public double Side;
    public Square(double s) { Side = s; }
    public override double Area() => Side * Side;
}

class Program
{
    static void Main(string[] args)
    {
        List<Shape> shapes = new List<Shape> { new Circle(2), new Square(3) };

        foreach (Shape s in shapes)
        {
            Console.WriteLine(s.Area());
        }
    }
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.