Inheritance: The Family Tree

Inheritance: The Family Tree in C#: A family business passes its trade down. The grandparent was a baker, so every child knows how to bake — they inherited the…

The Analogy: The Family Trade

A family business passes its trade down. The grandparent was a baker, so every child knows how to bake — they inherited the recipes without being taught from scratch. One child then specialises in wedding cakes: same flour, same oven, extra piping. Another keeps the recipes exactly as they were.

Inheritance is that. class Manager : Employee says "a Manager is an Employee, plus more". Everything Employee can do, Manager can do, without a line being copied. Where the family recipe needs adjusting, the child overrides it; where it does not, the child simply uses it.

Two limits come with the analogy. A class has exactly one base class — C# has no two-parent inheritance, because a diamond of conflicting recipes has no honest resolution. And the relationship must genuinely be "is a": a Manager is an Employee, but a Payslip is not, even though it uses one. When you catch yourself inheriting to reuse a method rather than to be the base type, you want a field, not a base class.


Syntax or Core Structure

using System;

class Employee
{
    public string Name { get; }
    protected decimal BaseSalary { get; }        // derived classes only

    public Employee(string name, decimal baseSalary)
    {
        Name = name;
        BaseSalary = baseSalary;
    }

    public virtual decimal MonthlyPay() => BaseSalary / 12m;

    public override string ToString() =>
        $"{GetType().Name,-12}{Name,-8}{MonthlyPay(),9:F2}";
}

class Manager : Employee
{
    private readonly int reports;

    public Manager(string name, decimal baseSalary, int reports)
        : base(name, baseSalary)                 // the base constructor runs first
    {
        this.reports = reports;
    }

    public override decimal MonthlyPay() => base.MonthlyPay() + reports * 50m;
}

class Contractor : Employee
{
    private readonly int hoursPerMonth;
    private readonly decimal hourlyRate;

    public Contractor(string name, int hoursPerMonth, decimal hourlyRate)
        : base(name, 0m)
    {
        this.hoursPerMonth = hoursPerMonth;
        this.hourlyRate = hourlyRate;
    }

    public override decimal MonthlyPay() => hoursPerMonth * hourlyRate;
}

class Program
{
    static void Main()
    {
        Employee[] staff =
        {
            new Employee("Ada", 60000m),
            new Manager("Grace", 84000m, 6),
            new Contractor("Alan", 80, 45m),
        };

        foreach (Employee e in staff)
            Console.WriteLine(e);                // one call site, three behaviours

        decimal payroll = 0m;
        foreach (Employee e in staff) payroll += e.MonthlyPay();
        Console.WriteLine($"payroll {payroll:F2}");

        Employee second = staff[1];
        Console.WriteLine($"is Manager: {second is Manager}");
        if (second is Manager m) Console.WriteLine($"downcast ok: {m.Name}");
        Console.WriteLine($"as Contractor is null: {(second as Contractor) is null}");
    }
}

Output:

Employee    Ada       5000.00
Manager     Grace     7300.00
Contractor  Alan      3600.00
payroll 15900.00
is Manager: True
downcast ok: Grace
as Contractor is null: True

ToString was written once, in Employee, and yet it printed the right type name and the right pay for all three. GetType() reports the object's real type regardless of the variable's declared type, and MonthlyPay() inside the base method dispatched to the override — that is the whole payoff of virtual.


Technical Depth: Override, Hide, and the Order Things Run In

The four keywords

KeywordMeaningDispatch when called through a base reference
virtualthis member may be replaced by a derived classruns the derived version
overridereplaces the base memberruns the derived version
newhides the base member with an unrelated oneruns the base version
sealed overridereplaces it, and forbids further overridingruns this version

The dangerous row is new. Hiding compiles and looks like overriding, but dispatch depends on the variable's type rather than the object's:

class A { public virtual string Who() => "A"; }
class B : A { public override string Who() => "B"; }
class C : A { public new string Who() => "C"; }     // hides, does not override

A b = new B();  Console.WriteLine(b.Who());   // B  - the object decides
A c = new C();  Console.WriteLine(c.Who());   // A  - the variable decides

Redeclaring a base member without new or override gives warning CS0108, "hides inherited member". That warning is almost always a bug: you meant override and the base member was not virtual, or you did not realise the name was taken.

Constructor order

For new Manager(...) the runtime does this, in order:

  1. Manager's own field initialisers
  2. Employee's field initialisers
  3. Employee's constructor body
  4. Manager's constructor body

Which produces a genuine trap: if the base constructor calls a virtual method, the override runs while the derived object's constructor body has not yet executed.

class Base
{
    public Base() => Console.WriteLine(Describe());     // calls the override, too early
    public virtual string Describe() => "base";
}

class Derived : Base
{
    private string label;
    public Derived() => label = "ready";
    public override string Describe() => label.ToUpper();   // NullReferenceException
}

So never call a virtual member from a constructor. Initialise in the constructor and let callers invoke the virtual member afterwards.

Casting up and down

Upcasting is implicit and always safe, because a Manager is an Employee. Downcasting is a claim about the runtime type and has three forms:

Manager m1 = (Manager)e;        // throws InvalidCastException if wrong
Manager? m2 = e as Manager;     // null if wrong, no exception
if (e is Manager m3) { ... }    // tests and binds in one step - prefer this

Nothing is lost on the way up. Unlike C++, C# stores a reference to the whole object, so there is no slicing: an Employee variable holding a Manager still carries every Manager field, waiting for the cast back down.

protected, sealed, and covariant returns

protected is the member visibility that exists for inheritance: derived classes may read BaseSalary, outside callers may not. Prefer protected over public for anything a subclass needs and the world does not — and prefer private over protected where you can, since protected is part of your public contract to every future subclass.

sealed on a class forbids inheritance entirely and lets the JIT turn virtual calls into direct ones. Sealing by default and unsealing deliberately is a defensible policy: an unsealed class is a promise that every virtual member behaves sensibly when replaced.

Since C# 9 an override may narrow its return type, which removes a great many casts:

class Employee   { public virtual Employee Clone() => new Employee(Name, BaseSalary); }
class Manager : Employee { public override Manager Clone() => new Manager(...); }

When not to inherit

Inheritance couples you to the base class permanently: its fields, its constructor requirements, its future changes. Two tests before you use it. Can you say "a D is an B" without wincing? And would every method that accepts a B still behave correctly if handed a D? That second one is the Liskov substitution principle, and the classic violation is a ReadOnlyList deriving from List whose Add throws — every caller of List.Add was told it worked. If either test fails, hold the base type in a field and delegate instead.


Real World Example: Shipping Rates by Parcel Type

Every parcel has a reference, a weight and a price. What differs between a letter, a standard parcel and a pallet is the handling fee, the label wording and — for pallets — a fragile surcharge. That is exactly the shape inheritance is for: one base holding everything common, three small overrides holding the differences.

using System;
using System.Collections.Generic;

class Parcel
{
    private const decimal PerKg = 1.20m;

    public string Reference { get; }
    public double WeightKg { get; }

    public Parcel(string reference, double weightKg)
    {
        if (weightKg <= 0)
            throw new ArgumentOutOfRangeException(nameof(weightKg), weightKg, "must be positive");
        Reference = reference;
        WeightKg = weightKg;
    }

    public virtual decimal Handling => 1.50m;
    public virtual string Kind => "parcel";
    public virtual decimal Cost() => Handling + (decimal)WeightKg * PerKg;

    // Not virtual: the shape of a label never varies, only the parts it asks for.
    public string Label() =>
        $"{Reference,-8}{Kind,-9}{WeightKg,6:F1} kg{Cost(),9:F2}";
}

class Letter : Parcel
{
    public Letter(string reference, double weightKg) : base(reference, weightKg)
    {
        if (weightKg > 2.0)
            throw new ArgumentOutOfRangeException(nameof(weightKg), weightKg, "letters max 2 kg");
    }

    public override string Kind => "letter";
    public override decimal Handling => 0.60m;
}

class Pallet : Parcel
{
    private readonly bool fragile;

    public Pallet(string reference, double weightKg, bool fragile)
        : base(reference, weightKg) => this.fragile = fragile;

    public override string Kind => fragile ? "pallet!" : "pallet";
    public override decimal Handling => 12.00m;
    public override decimal Cost() => base.Cost() * (fragile ? 1.25m : 1m);
}

class Program
{
    static void Main()
    {
        var shipment = new List<Parcel>
        {
            new Letter("SH-01", 0.5),
            new Parcel("SH-02", 4.0),
            new Pallet("SH-03", 120.0, false),
            new Pallet("SH-04", 80.0, true),
        };

        decimal total = 0m;
        foreach (Parcel p in shipment)
        {
            Console.WriteLine(p.Label());
            total += p.Cost();
        }

        Console.WriteLine($"{"total",-8}{shipment.Count,9} items{total,12:F2}");

        try { var bad = new Letter("SH-05", 3.0); }
        catch (ArgumentOutOfRangeException ex) { Console.WriteLine($"rejected {ex.ParamName}"); }
    }
}

Output:

SH-01   letter      0.5 kg     1.20
SH-02   parcel      4.0 kg     6.30
SH-03   pallet    120.0 kg   156.00
SH-04   pallet!    80.0 kg   135.00
total           4 items      298.50
rejected weightKg

Label() is the piece worth studying. It is deliberately not virtual: the column layout is a decision for the shipping system, not for each parcel type, and it calls the virtual Kind, WeightKg and Cost() to fill the slots. Adding an Envelope class means overriding two members and touching no formatting code at all. That inversion — a fixed skeleton calling replaceable parts — is the template method pattern, and it is inheritance at its most useful.

Letter shows the ordering rule in practice. Its own constructor cannot reject a 3 kg weight before Parcel's constructor has run, so the base object is fully built and then the derived check throws. That is fine here, but it is why tightening a base class's validation in a subclass is a smell: the object briefly existed in a state the subclass forbids.

Note also Pallet.Cost() calling base.Cost() rather than restating the formula. The per-kilo rate lives in exactly one place, and the fragile surcharge is expressed as what it actually is — a multiplier on the normal price.


Common Mistakes

  1. Redeclaring a base member without override, so the compiler quietly hides it (CS0108) and calls through a base reference run the base version.
  2. Forgetting virtual on the base member. Without it the derived member cannot override, and new is not the fix you want.
  3. Calling a virtual method from a constructor. The override runs before the derived constructor body, so its fields are still null or zero.
  4. Inheriting for code reuse rather than because the "is a" relationship holds. A Payslip that inherits Employee to reach BaseSalary should hold an Employee field instead.
  5. Downcasting with a hard cast and meeting InvalidCastException in production. Use is T x and handle the false branch.
  6. Making everything protected so subclasses can "just get at it". Every protected member is a promise to every future subclass; keep what you can private.
  7. Overriding a member to throw NotSupportedException, breaking the substitution guarantee every caller of the base type relies on.
  8. Building a five-level hierarchy where a change to the root ripples through all of it. Two or three levels is usually the honest depth; beyond that, prefer composition or interfaces.

Best Practices

  • Say the sentence out loud — "a Manager is an Employee" — before writing the colon. If it needs a caveat, use a field instead.
  • Mark only the members you intend to be replaced as virtual, and document what an override must preserve.
  • Keep the common skeleton non-virtual and let it call small virtual parts, as Label() does above.
  • Call base.Method() from an override when you are extending behaviour rather than replacing it, so the formula lives in one place.
  • Chain constructors with : base(...) and validate each class's own arguments in its own constructor.
  • Prefer protected to public for subclass-only members, and private to protected wherever possible.
  • Seal classes and overrides that are not designed for further extension; it documents intent and helps the JIT.
  • Override ToString() once in the base using GetType().Name, so every derived type gets a useful log line for free.

Practice Exercises

  1. Build a Shape base class with a Name property and virtual double Area() returning 0, then Circle, Rectangle and Triangle overrides. Put five shapes in a Shape[], print each with a single overridden ToString() in the base, and print the total area.
  2. Write Account with a virtual decimal MonthlyFee() of 5.00m, then StudentAccount (fee zero) and BusinessAccount (fee 5.00m plus 0.50m per transaction, using base.MonthlyFee()). Total the fees for a mixed array and print each account's own figure alongside it.
  3. Reproduce the hiding trap: write A with virtual string Who(), B overriding it, and C hiding it with new. Print the result of calling Who() through both an A variable and a correctly-typed variable for each, then explain the four lines of output in your own words.
  4. Reproduce the constructor-order trap: a base whose constructor calls a virtual Describe(), and a derived class whose override reads a field set in its own constructor. Run it, note the exception, then fix it two ways — once by removing the virtual call from the constructor, once by giving the field an initialiser — and say which fix you would ship.