CodeBlanks Logo Icon CodeBlanks

Polymorphism basics

C# course · Intermediate · Lesson 59/116

Learn that the same call behaves differently on different types.

What is polymorphism?

Polymorphism means the same call behaves differently on different types. If a base Shape class marks its Draw method as virtual, a derived Circle can replace it with override.

The key point: when you write Shape s = new Circle();, the call s.Draw() looks at the object's runtime type and runs Circle.Draw. This delayed choice is the heart of polymorphism. The same code, different objects, different results.

A base reference holds a derived object

The practical side of polymorphism is this: a base class reference can hold a derived object. A List<Shape> can contain Circle, Square and Triangle.

Then a single foreach loop calls Draw on each. Every object runs its own drawing method. This makes the code type-agnostic: when a new shape is added, you do not touch the loop.

Exercise Polymorphism with Shape and Circle

Define a Shape class with a virtual void Draw() method that prints Console.WriteLine("Drawing shape"). Define Circle : Shape that overrides Draw and prints Console.WriteLine("Drawing circle"). In Main put both in a List<Shape> and call Draw in a foreach.

Show example solution
Shape { public override void Draw() { Console.WriteLine("Drawing circle"); } }. In Main build a List<Shape> and call Draw in a foreach.
Example solution:
using System;
using System.Collections.Generic;

class Shape
{
    public virtual void Draw()
    {
        Console.WriteLine("Drawing shape");
    }
}

class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing circle");
    }
}

class Program
{
    static void Main()
    {
        var shapes = new List<Shape> { new Circle(), new Shape() };
        foreach (var s in shapes)
        {
            s.Draw();
        }
    }
}

Test yourself

  1. What does this code print?

    Shape s = new Circle();
    s.Draw();
    // Circle.Draw overrides
    • Circle.Draw runs
    • Shape.Draw runs
    • A compile error occurs
    • A runtime error is thrown
    Show answer

    Circle.Draw runs — Correct. The runtime type of the object is selected: Circle.Draw.

  2. The overridable keyword

    public ____ void Draw() { }
    Show answer
    public virtual void Draw() { }
  3. Match each keyword to its meaning

    virtual
    Can be overridden
    override
    Replaces base method
    sealed
    Stops further deriving
    base
    Calls the base class

All lessons in Intermediate