Polymorphism: The Many Faces

Polymorphism: The Many Faces in C#: A conductor raises the baton and gives one instruction: play.

The Analogy: The Conductor's Downbeat

A conductor raises the baton and gives one instruction: play. The violins draw a bow, the drums get struck, the flutes are blown. One instruction, thirty different physical actions, and the conductor does not need to know how any instrument works — only that each of them understands play.

That is polymorphism. foreach (Instrument i in band) i.Play(); is the downbeat. The loop contains no type tests, no switch, no list of special cases; each object supplies its own performance and the call site stays one line long. Add a harp next season and the loop does not change.

The word means "many shapes", and C# gives it to you in three distinct ways. Overriding picks the behaviour from the object at run time — the conductor case. Overloading picks a method from the argument types at compile time. Generics write one algorithm that works for many types without knowing them. They are easy to confuse and they fail in different ways, so it is worth being precise about which one is in play.


Syntax or Core Structure

using System;
using System.Linq;

class Instrument
{
    public string Name { get; }
    public Instrument(string name) => Name = name;
    public virtual string Play() => "...";
}

class Violin : Instrument
{
    public Violin() : base("violin") { }
    public override string Play() => "screeee";
}

class Drum : Instrument
{
    public Drum() : base("drum") { }
    public override string Play() => "boom";
}

class Program
{
    // Three overloads: chosen by the compiler, from the argument's static type.
    static string Label(object o) => $"object:{o}";
    static string Label(int n) => $"int:{n}";
    static string Label(double d) => $"double:{d}";

    static void Main()
    {
        Instrument[] band = { new Violin(), new Drum(), new Instrument("triangle") };
        foreach (Instrument i in band)
            Console.WriteLine($"{i.Name,-9}{i.Play()}");

        Instrument one = new Drum();                    // declared base, built derived
        Console.WriteLine($"declared Instrument, plays {one.Play()}");

        object boxed = 5;                               // still an int at run time
        Console.WriteLine($"{Label(5)} / {Label(5.0)} / {Label(boxed)}");

        Console.WriteLine(string.Join(" | ", band.Select(i => i.Play())));
    }
}

Output:

violin   screeee
drum     boom
triangle ...
declared Instrument, plays boom
int:5 / double:5 / object:5
screeee | boom | ...

Put the fourth and fifth lines side by side, because together they are the whole distinction. one.Play() was called through an Instrument variable and still printed boom — overriding consults the object. Label(boxed) was passed an int in an object variable and still printed object:5 — overloading consults the variable, at compile time, and never looks at what is actually in there.


Technical Depth: Three Kinds, One Table

OverridingOverloadingGenerics
Also calledruntime, subtype polymorphismcompile-time, ad hoc polymorphismparametric polymorphism
Decided bythe object's real type, at run timethe arguments' static types, at compile timethe type argument, at compile time
Signatureidentical to the base membersame name, different parametersone method, many types
Keywordvirtual plus overridenone<T>
Extend byadding a classadding a methodadding a call site

How overriding actually works

Every object of a class with virtual members carries a hidden pointer to a method table for its real type. A virtual call reads that table and jumps — one extra indirection, a few nanoseconds, and nothing you should ever optimise away by hand. Non-virtual and sealed calls skip the table, which is why sealing helps the JIT.

The consequence worth remembering: virtual dispatch is decided by the object, so a base-class method calling a virtual member gets the derived version. That is what made ToString() in the previous lesson print the right pay for all three staff types.

Overload resolution surprises

The compiler picks the most specific applicable overload, using only static types:

static void Show(long x)  => Console.WriteLine("long");
static void Show(double x) => Console.WriteLine("double");

Show(5);          // long   - int widens to long more cheaply than to double
Show(5.0f);       // double - float widens to double
Show(null);       // will not compile against these two: neither accepts null

Three rules save most of the pain. An exact match beats any conversion; a narrower numeric conversion beats a wider one; and a params overload is the last resort, chosen only when nothing fixed fits. When two candidates are equally good the result is CS0121, "ambiguous call", and the fix is a cast at the call site rather than another overload.

Operator overloading

Operators are static methods with special names, and giving a type its own arithmetic is how decimal, DateTime and TimeSpan read so naturally:

readonly struct Money
{
    public decimal Amount { get; }
    public Money(decimal amount) => Amount = amount;

    public static Money operator +(Money a, Money b) => new(a.Amount + b.Amount);
    public static Money operator *(Money m, int n) => new(m.Amount * n);
    public static bool operator >(Money a, Money b) => a.Amount > b.Amount;
    public static bool operator <(Money a, Money b) => a.Amount < b.Amount;

    public static explicit operator decimal(Money m) => m.Amount;   // (decimal)money
    public override string ToString() => $"{Amount:F2}";
}

C# insists on symmetry: > requires <, == requires !=, and overloading == without overriding Equals and GetHashCode earns a warning and deserves it. Conversion operators come in implicit and explicit flavours — make it explicit whenever information can be lost or a caller might be surprised.

Generics: one algorithm, many types

static T Largest<T>(T[] items) where T : IComparable<T>
{
    T best = items[0];
    foreach (T item in items)
        if (item.CompareTo(best) > 0) best = item;
    return best;
}

Largest(new[] { 3, 9, 4 });                 // 9
Largest(new[] { "pear", "apple" });         // pear

The where constraint is what makes this real polymorphism rather than casting: inside the method T is known to have CompareTo, so the compiler checks the body once and every call site is type-safe. Unlike Java, C# generics survive to run time, so List<int> genuinely stores unboxed ints.

The alternative: switching on type

Pattern matching can do the same job as virtual dispatch, and the trade-off is exactly opposite:

static string Play(Instrument i) => i switch
{
    Violin => "screeee",
    Drum => "boom",
    _ => "...",
};

With virtual, adding an instrument is cheap and adding an operation means editing every class. With switch, adding an operation is cheap and adding an instrument means editing every switch. Choose by asking which axis is going to grow: closed set of types with many operations favours switch, open set of types with few operations favours virtual.


Real World Example: A Dashboard of Mixed Widgets

A status dashboard is polymorphism you can see. The frame knows the width, the border and the order; it knows nothing about gauges or lists. Each widget reports how many rows it needs and renders one row on request, and the frame's loop never grows a special case.

using System;
using System.Collections.Generic;

class Widget
{
    public string Title { get; }
    protected Widget(string title) => Title = title;

    public virtual int Rows => 1;
    public virtual string Line(int row) => Title;
}

class Label : Widget
{
    public Label(string text) : base(text) { }     // inherits both defaults unchanged
}

class Gauge : Widget
{
    private const int BarWidth = 10;
    private readonly int percent;

    public Gauge(string title, int percent) : base(title) => this.percent = percent;

    public override string Line(int row)
    {
        int filled = percent * BarWidth / 100;
        return $"{Title,-8}[{new string('#', filled)}{new string('.', BarWidth - filled)}]{percent,4}%";
    }
}

class ListWidget : Widget
{
    private readonly string[] items;

    public ListWidget(string title, params string[] items) : base(title) => this.items = items;

    public override int Rows => 1 + items.Length;

    public override string Line(int row) =>
        row == 0 ? $"{Title}:" : $"  - {items[row - 1]}";
}

class Dashboard
{
    private const int Width = 26;
    private readonly List<Widget> widgets = new();

    public void Add(Widget w) => widgets.Add(w);

    public int TotalRows
    {
        get
        {
            int n = 0;
            foreach (Widget w in widgets) n += w.Rows;
            return n;
        }
    }

    public void Render()
    {
        string border = "+" + new string('-', Width + 2) + "+";
        Console.WriteLine(border);

        foreach (Widget w in widgets)              // no type tests anywhere below
            for (int r = 0; r < w.Rows; r++)
                Console.WriteLine($"| {w.Line(r).PadRight(Width)} |");

        Console.WriteLine(border);
        Console.WriteLine($"{widgets.Count} widgets, {TotalRows} rows");
    }
}

class Program
{
    static void Main()
    {
        var d = new Dashboard();
        d.Add(new Label("Build 482 - green"));
        d.Add(new Gauge("coverage", 87));
        d.Add(new Gauge("cpu", 42));
        d.Add(new ListWidget("failing", "auth timeout", "flaky upload"));
        d.Render();
    }
}

Output:

+----------------------------+
| Build 482 - green          |
| coverage[########..]  87%  |
| cpu     [####......]  42%  |
| failing:                   |
|   - auth timeout           |
|   - flaky upload           |
+----------------------------+
4 widgets, 6 rows

Label overrides nothing at all — it exists purely to be a Widget whose defaults are already correct, which is a perfectly respectable subclass. Gauge overrides only Line. ListWidget overrides both, and its variable row count is what forces the frame to ask Rows rather than assume one line each; TotalRows then falls out of the same virtual property.

The measure of the design is what adding a Sparkline widget would cost: one class, two overrides, one Add call, and not a single edit inside Dashboard. Had Render been written as a switch over widget types — case Gauge g: ... — every new widget would mean reopening the frame, and the compiler would not remind you to.


Common Mistakes

  1. Expecting an overload to be chosen from the runtime type. Label(boxed) picks the object overload because overload resolution happens at compile time and never inspects the contents.
  2. Confusing overloading with overriding, then wondering why a "polymorphic" call runs the wrong version. Different parameters means a different method, not a replacement.
  3. Forgetting virtual on the base member, so the derived version merely hides it and base-typed loops call the wrong code.
  4. Writing a switch over types inside a base-class method. If the base knows all its subclasses, the virtual member is missing.
  5. Overloading on types that convert into each other — Show(long) and Show(double) — and being surprised which one wins. Prefer distinct parameter counts or distinct names.
  6. Overloading == without overriding Equals and GetHashCode, so the operator and the dictionary disagree about equality.
  7. Making a conversion operator implicit when it loses information, so precision silently disappears at call sites nobody wrote deliberately.
  8. Reaching for dynamic to get late binding when a virtual member or a generic constraint would do it with compile-time checking.

Best Practices

  • Let the objects decide. If a loop tests types to choose behaviour, move that behaviour onto the types as a virtual member.
  • Keep the skeleton in the base and the differences in small overrides, so a new subclass is additive.
  • Use overloads only for genuinely equivalent operations on different input shapes; if the behaviour differs, give it a different name.
  • Constrain generics with where so the body is checked once and every call site is safe, instead of casting inside.
  • Overload operators only where the arithmetic is uncontroversial — money, vectors, durations — and keep the pairs symmetrical.
  • Prefer explicit conversion operators unless the conversion is lossless and obvious.
  • Choose between virtual and a type switch by which axis will grow: new types favour virtual, new operations favour switch.
  • Seal classes and overrides you do not intend to be extended further; it documents the design and speeds up dispatch.

Practice Exercises

  1. Write an Animal base with virtual string Speak(), plus Dog, Cat and Cow overrides. Fill an Animal[] with six animals, print each with a single ToString() written once in the base using GetType().Name, then add a Fox that overrides nothing and explain what it prints and why.
  2. Demonstrate the overloading-versus-overriding gap in one program: write Describe(object), Describe(string) and Describe(int), call all three with correctly-typed variables and again with object-typed variables, and write three sentences explaining the six lines of output.
  3. Build the Money struct from the depth section with +, *, >, <, an explicit conversion to decimal, and an overridden ToString(). Total an array of five Money values, find the largest with a generic Largest<T> constrained on IComparable<T>, and print both.
  4. Add a Sparkline widget to the dashboard above that renders one row from an int[] of values using the characters _ - = for low, middle and high, then add a Separator widget of one row of dashes. Confirm that Dashboard needed no edits, and write two sentences on what a switch-based Render would have cost instead.