Skip to content
Codewilds

Lesson 27 of 34 · Inheritance & Interfaces

Polymorphism in C#: One Interface, Many Forms

medium20 XP3 min read

Polymorphism — Greek for many forms — is the payoff of inheritance and interfaces. Code written against a base class or an interface works with every derived type, and each object automatically uses its own version of the overridden methods. You can add new kinds of objects without touching the code that uses them.

Virtual dispatch

When a method is virtual (or abstract), C# decides at runtime, based on the actual object, which override to call:

public abstract class Instrument
{
    public abstract string Play();
}

public class Drum : Instrument { public override string Play() => "Boom"; }
public class Flute : Instrument { public override string Play() => "Tweet"; }

List<Instrument> band = [new Drum(), new Flute(), new Drum()];
foreach (Instrument i in band)
{
    Console.Write(i.Play() + " ");   // Boom Tweet Boom
}

The loop only knows about Instrument, yet every object plays its own sound. Adding a Harp later requires no change to the loop. That is the heart of good object-oriented design: code that is open for extension but closed for modification.

Static type vs runtime type

In Instrument i = new Drum(); the variable's static type is Instrument — it decides which members you may call. The object's runtime type is Drum — it decides which override runs. i.GetType().Name returns "Drum".

Type patterns: is and switch

Sometimes you do need to know the concrete type, for example when handling values of completely unrelated types. Type patterns test the type and give you a typed variable at once:

object loot = 25;
if (loot is int coins && coins > 10)
{
    Console.WriteLine($"{coins} coins!");
}

A switch expression with type patterns handles many cases neatly. Arms are checked from top to bottom, so put the most specific ones first. Property patterns ({ Length: > 3 }) and when clauses refine a match:

string Describe(object? item) => item switch
{
    null => "empty hands",
    int n when n < 0 => "a debt",
    int n => $"{n} gold",
    string { Length: > 3 } s => $"a long note: {s}",
    string s => $"a note: {s}",
    Instrument i => $"an instrument that goes {i.Play()}",
    _ => "something strange",
};

The as operator is the older, softer cast: var drum = thing as Drum; gives null instead of throwing when thing is not a Drum.

Prefer virtual methods over type checks

If you find yourself writing if (x is Drum) ... else if (x is Flute) ... for your own classes, a virtual method is usually the better design: each class knows its own behaviour. Type patterns shine at the edges of a program, where data of unrelated types arrives.

Common mistakes

  • Hiding instead of overriding: a method declared without override (or with new) is not called through a base reference.
  • Ordering switch arms badly: Creature c before Dragon d swallows the dragons — the compiler even reports the later arm as unreachable.
  • Casting blindly: (Dragon)creature throws an InvalidCastException for a goblin.

Assignment

The abstract Creature class is given. Complete:

  1. Goblin says "Gimme shinies!" with threat 2; Dragon says "ROAR" with threat 10 + Age / 100; Slime says "blub" and keeps the default threat (1).
  2. Bestiary.Chorus(creatures) joins what every creature says with " / ".
  3. Bestiary.TotalThreat(creatures) adds up all threats.
  4. Bestiary.Identify(thing) describes any object: null → "nothing"; a dragon with threat 15 or more → "an ancient dragon called <Name>"; any other creature → "a creature called <Name>"; an int → "the number <n>"; a string → "a scroll reading <text>"; anything else → "something unknown".

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Polymorphism in other languages

Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.

Lesson last updated on .

Write code ↓
C#+20 XP

Lesson 27 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn C# course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.