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

Polymorphism

Polymorphism means many forms: different objects can answer the same command in their own ways. Tell every animal to speak, and the dog barks while the cat meows.

In this page:

  1. Polymorphism
Syntax
csharp
BaseType variable = new DerivedType();
variable.MethodName();   // runs the DerivedType override

List<BaseType> items = new List<BaseType> { new DerivedA(), new DerivedB() };

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());
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting virtual and override, so the base version is called through a base reference.
  2. Calling a derived-only method through a base reference, which does not compile.
  3. Confusing method hiding with new with true overriding.
Chapter Summary
  • Inheritance lets a class reuse another class, with base accessing the parent.
  • Method overriding and polymorphism let derived classes change behavior.
  • Abstract and sealed classes control how classes can be extended.
🔒

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.