TExcelTAD
Home › C# › C# Polymorphism

C# Polymorphism

Polymorphism ("many forms") means that code written against a base type works with any of its derived types — and each object responds in its own way. You call shape.Area() without knowing whether the shape is a circle or a square, and the right calculation happens automatically.

Virtual dispatch

When a method is virtual and overridden, the version that runs is chosen at run time based on the actual type of the object, not the declared type of the variable.

csharp · try it yourself
using System;
using System.Collections.Generic;

var payments = new List<Payment>
{
    new CardPayment(50m),
    new PayPalPayment(20m),
    new CashPayment(12.5m),
};

decimal total = 0;
foreach (Payment p in payments)
{
    Console.WriteLine(p.Process());
    total += p.Amount;
}
Console.WriteLine(
quot;Total: {total}"); class Payment { public decimal Amount { get; } public Payment(decimal amount) => Amount = amount; public virtual string Process() =>
quot;Processing {Amount}"; } class CardPayment : Payment { public CardPayment(decimal amount) : base(amount) { } public override string Process() =>
quot;Charging card {Amount} (+fee {Amount * 0.02m})"; } class PayPalPayment : Payment { public PayPalPayment(decimal amount) : base(amount) { } public override string Process() =>
quot;Redirecting to PayPal for {Amount}"; } class CashPayment : Payment { public CashPayment(decimal amount) : base(amount) { } // no override: uses the base version }
Charging card 50 (+fee 1.00)
Redirecting to PayPal for 20
Processing 12.5
Total: 82.5

The loop has no if (p is CardPayment) … chains. Adding a new payment type later means writing one new class — the loop does not change at all. That is the real payoff of polymorphism.

override versus new

If a derived class declares a method with the same name without override, it hides the base method instead of replacing it. The compiler warns you; you can silence the warning with the new modifier. Hidden methods are chosen by the declared type of the variable, which is rarely what you want:

csharp · try it yourself
using System;

Base a = new Derived();
Derived b = new Derived();

a.Virtual();   // runtime type decides
a.Hidden();    // declared type (Base) decides
b.Hidden();

class Base
{
    public virtual void Virtual() => Console.WriteLine("Base.Virtual");
    public void Hidden() => Console.WriteLine("Base.Hidden");
}

class Derived : Base
{
    public override void Virtual() => Console.WriteLine("Derived.Virtual");
    public new void Hidden() => Console.WriteLine("Derived.Hidden");
}
Derived.Virtual
Base.Hidden
Derived.Hidden
override new (hiding)
Base member must be virtual, abstract or override Anything
Method chosen by Runtime type of the object Compile-time type of the variable
Typical use Customising behaviour (almost always) Rare compatibility situations

Overriding ToString and Equals

System.Object defines virtual methods that every class can override. Overriding ToString gives objects a readable representation everywhere they are printed:

csharp · try it yourself
using System;

object[] things = { new Money(9.5m, "EUR"), 42, "text", new Money(3m, "USD") };
foreach (object o in things)
    Console.WriteLine(o.ToString());

class Money
{
    public decimal Amount { get; }
    public string Currency { get; }
    public Money(decimal amount, string currency) { Amount = amount; Currency = currency; }
    public override string ToString() => 
quot;{Amount:F2} {Currency}"; }
9.50 EUR
42
text
3.00 USD

Even int and string participate: each type overrides ToString in its own way.

Type checks and casts

Sometimes you do need the specific type. Pattern matching with is checks and converts in one step; as returns null instead of throwing when the cast fails.

csharp · try it yourself
using System;

Animal[] animals = { new Dog(), new Bird(), new Dog() };

foreach (Animal a in animals)
{
    if (a is Bird bird)
        bird.Fly();
    else
        Console.WriteLine(
quot;{a.GetType().Name} cannot fly"); } Dog d = animals[1] as Dog; Console.WriteLine(d == null ? "Not a dog" : "A dog"); class Animal { } class Dog : Animal { } class Bird : Animal { public void Fly() => Console.WriteLine("Bird is flying"); }
Dog cannot fly
Bird is flying
Dog cannot fly
Not a dog

Tip: If you find yourself writing many is checks to decide what to do, consider moving that behaviour into a virtual method instead. Let the objects decide.

Two kinds of polymorphism

Kind Decided at C# mechanism
Compile-time (static) Compile time Method overloading, generics
Run-time (dynamic) Run time virtual/override, interfaces

Test yourself

Animal a = new Dog(); a.Speak(); — Speak is virtual and Dog overrides it. Which version runs?

  1. Animal.Speak
  2. Dog.Speak
  3. Both
  4. Compile error

What does the as operator return when the conversion fails?

  1. An exception
  2. false
  3. null
  4. The original object

A method in a derived class marked new instead of override is chosen based on…

  1. The runtime type of the object
  2. The declared type of the variable
  3. Random choice
  4. The newest class