Abstraction: The Universal Standard

Abstraction: The Universal Standard in C#: Imagine a recipe card headed "Pie". Every step is printed: line the tin, blind-bake the base, add the filling of…

The Analogy: The Recipe With a Hole In It

Imagine a recipe card headed "Pie". Every step is printed: line the tin, blind-bake the base, add the filling of your choice, seal the lid, forty minutes at 190C, rest before slicing. Only one step is left blank, and it is left blank deliberately — because everything except the filling is the same for every pie in the book.

You cannot cook "a pie". There is no such dish. You can cook an apple pie or a steak pie, each of which is that card plus one decision.

That is an abstract class. abstract class Report prints the heading, draws the rule, indents the rows and adds the footer; the one thing it refuses to guess is what the rows are, so it declares abstract string[] Rows(); — a step with no body — and the compiler then forbids anyone from instantiating Report and forces every subclass to fill the hole.

The wider sense of the word matters as much as the keyword. Abstraction is deciding what callers are allowed to know. The reporting system knows there is something that produces rows; it has no idea whether they came from a database, a CSV or a hard-coded array, and that ignorance is the feature.


Syntax or Core Structure

using System;

abstract class Report
{
    protected Report(string title) => Title = title;   // protected: only subclasses call it

    public string Title { get; }

    public abstract string[] Rows();              // no body - every report must supply one
    protected virtual string Footer => "";        // has a default - override only if wanted

    // Fixed skeleton, deliberately not virtual: every report prints the same way.
    public void Print()
    {
        Console.WriteLine(Title.ToUpper());
        Console.WriteLine(new string('=', Title.Length));
        foreach (string row in Rows()) Console.WriteLine($"  {row}");
        if (Footer.Length > 0) Console.WriteLine(Footer);
        Console.WriteLine();
    }
}

class SalesReport : Report
{
    private readonly (string Region, decimal Amount)[] data;

    public SalesReport((string Region, decimal Amount)[] data)
        : base("sales by region") => this.data = data;

    public override string[] Rows()
    {
        var rows = new string[data.Length];
        for (int i = 0; i < data.Length; i++)
            rows[i] = $"{data[i].Region,-8}{data[i].Amount,10:F2}";
        return rows;
    }

    protected override string Footer
    {
        get
        {
            decimal total = 0m;
            foreach (var d in data) total += d.Amount;
            return $"  {"total",-8}{total,10:F2}";
        }
    }
}

class EmptyReport : Report
{
    public EmptyReport() : base("no data") { }
    public override string[] Rows() => Array.Empty<string>();   // Footer default is fine
}

class Program
{
    static void Main()
    {
        // Report r = new Report("x");   // CS0144: cannot create an instance of an abstract class

        Report[] reports =
        {
            new SalesReport(new[] { ("north", 1200.50m), ("south", 980.00m), ("west", 1420.25m) }),
            new EmptyReport(),
        };

        foreach (Report r in reports) r.Print();
        Console.WriteLine($"printed {reports.Length} reports");
    }
}

Output:

SALES BY REGION
===============
  north      1200.50
  south       980.00
  west       1420.25
  total      3600.75

NO DATA
=======

printed 2 reports

EmptyReport is eleven characters of real work: one constructor call and one Rows() override. Everything else — the upper-cased heading, the rule of exactly the right length, the indentation, the decision to omit an empty footer — was written once in the abstract base and can never drift between report types.


Technical Depth: The Rules, and When a Hole Beats a Default

abstract versus virtual versus plain

plain membervirtualabstract
Has a bodyyesyesno
Can a subclass replace itnoyes, optionallyyes, and it must
Compiler enforces an overriden/anoyes (CS0534)
Right whenthe behaviour is fixed for all subtypesthere is a sensible defaultthere is no sensible default

That last row is the whole decision. Footer above is virtual because "no footer" is a perfectly good answer. Rows() is abstract because any default would be a lie — returning an empty array would let a subclass silently forget to implement the one thing it exists for.

The rules the compiler enforces

  • An abstract member forces the class to be abstract too.
  • An abstract class cannot be instantiated (CS0144), but it can have constructors, fields, state and concrete methods — subclass constructors call the base one through : base(...).
  • A concrete subclass must override every inherited abstract member (CS0534). An abstract subclass may leave some unfilled and pass the obligation down.
  • abstract cannot combine with private (nobody could implement it), static, sealed or virtual — an abstract member is implicitly virtual already.
  • protected abstract is legal and useful: a hook that subclasses must fill but outsiders cannot call.
  • abstract override re-opens a member that a base class had already implemented, forcing the next level down to supply it again.

Abstract classes carry state; that is the point

An interface, as the next lesson will show, cannot hold instance fields. An abstract class can, and that is usually the reason to pick one:

abstract class Job
{
    private static int nextId = 1;
    protected Job(string name) { Id = nextId++; Name = name; }

    public int Id { get; }               // shared plumbing every job gets for free
    public string Name { get; }
    protected abstract bool Execute(int attempt);
}

Rough guide, with the details in the next lesson: abstract class when subtypes share implementation and state and are genuinely a family; interface when unrelated types need to be usable in the same place. A type may implement many interfaces but inherit only one class, so an abstract base spends your single inheritance slot — spend it deliberately.

Abstraction as a design principle

The keyword is the small half of the word. The large half is depending on the shape of a thing rather than the thing:

abstract class OrderStore                                  // what callers may know
{
    public abstract Order? Find(int id);
    public abstract void Save(Order order);
}

class SqlOrderStore : OrderStore { ... }                   // what actually happens
class InMemoryOrderStore : OrderStore { ... }              // what the tests use

Code written against OrderStore can be tested without a database and re-pointed at a different one without editing. The measure of the abstraction is whether callers can be written without knowing which subclass they will get. When they cannot — when they must call Save twice for SQL but once for the in-memory version, or must know that one of them throws on a missing id and the other returns null — the abstraction leaks, and a leaky abstraction is worse than none because it hides the detail without removing the need to know it.

Keep the hole small

Every abstract member is an obligation on every future subclass. Six abstract methods means six things to get right before anything compiles, and it usually signals that two responsibilities are sharing one base class. One or two abstract members plus a fixed skeleton is the shape that ages well.


Real World Example: A Job Runner With a Shared Retry Policy

Retry logic is written wrong in most codebases because it is written repeatedly. An abstract base fixes the policy once — count the attempts, stop at the limit, catch and log a throw, record the outcome — and leaves each job to supply nothing but the work itself.

using System;
using System.Collections.Generic;

abstract class Job
{
    private static int nextId = 1;

    protected Job(string name)
    {
        Id = nextId++;
        Name = name;
    }

    public int Id { get; }
    public string Name { get; }
    public int Attempts { get; private set; }
    public bool Succeeded { get; private set; }

    protected abstract bool Execute(int attempt);   // the one thing a job must supply
    protected virtual int MaxAttempts => 3;         // most jobs are happy with three

    public void Run()                               // the policy, shared by every job
    {
        while (Attempts < MaxAttempts && !Succeeded)
        {
            Attempts++;
            try
            {
                Succeeded = Execute(Attempts);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"  job {Id} threw: {ex.Message}");
            }
        }
    }

    public override string ToString() =>
        $"{Id,-3}{Name,-12}{Attempts,3} attempt(s)  {(Succeeded ? "ok" : "FAILED")}";
}

class FlakyUpload : Job
{
    private readonly int succeedsOn;
    public FlakyUpload(int succeedsOn) : base("upload") => this.succeedsOn = succeedsOn;
    protected override bool Execute(int attempt) => attempt >= succeedsOn;
}

class Reindex : Job
{
    public Reindex() : base("reindex") { }
    protected override int MaxAttempts => 1;        // expensive: never retry
    protected override bool Execute(int attempt) => true;
}

class BrokenExport : Job
{
    public BrokenExport() : base("export") { }
    protected override bool Execute(int attempt) =>
        throw new InvalidOperationException("disk full");
}

class Program
{
    static void Main()
    {
        var jobs = new List<Job>
        {
            new FlakyUpload(2),
            new Reindex(),
            new BrokenExport(),
            new FlakyUpload(9),
        };

        foreach (Job j in jobs) j.Run();

        Console.WriteLine();

        int ok = 0, attempts = 0;
        foreach (Job j in jobs)
        {
            if (j.Succeeded) ok++;
            attempts += j.Attempts;
            Console.WriteLine(j);
        }

        Console.WriteLine($"{ok}/{jobs.Count} succeeded in {attempts} attempts");
    }
}

Output:

  job 3 threw: disk full
  job 3 threw: disk full
  job 3 threw: disk full

1  upload        2 attempt(s)  ok
2  reindex       1 attempt(s)  ok
3  export        3 attempt(s)  FAILED
4  upload        3 attempt(s)  FAILED
2/4 succeeded in 9 attempts

Notice what each subclass did not write. None of them counts attempts, none catches an exception, none decides when to give up, and none records success — Attempts and Succeeded have private set so a subclass physically cannot falsify them. FlakyUpload is three lines and gets a complete retry story.

MaxAttempts is virtual rather than abstract for the reason set out above: three is a defensible default, so most jobs should be able to say nothing. Reindex overrides it to 1 because retrying a full reindex is worse than failing. Execute, by contrast, is abstract, because a default implementation of "do the work" could only be a no-op that returned true — and a job that silently succeeds without doing anything is the worst bug in this file's design space.

The static nextId shows the other half of why this is an abstract class rather than an interface: it holds state, and the constructor guarantees every job gets an identity before any subclass code runs.


Common Mistakes

  1. Trying to new an abstract class and meeting CS0144. Instantiate a concrete subclass, or reconsider whether the class should be abstract at all.
  2. Making a member abstract when a sensible default exists, forcing every subclass to write boilerplate that could have been inherited.
  3. Giving an abstract member a fake default instead — an empty method or a return null — so a subclass that forgets to implement it fails silently at run time rather than loudly at compile time.
  4. Declaring an abstract member private. Nobody could ever implement it; use protected abstract for a subclass-only hook.
  5. Making the skeleton method virtual as well, so a subclass can override the whole algorithm and the shared policy quietly stops applying.
  6. Piling six or seven abstract members into one base class, so every new subclass is a day's work and the base clearly has more than one job.
  7. Spending the single inheritance slot on an abstract class that carries no state and no implementation. If it is only a list of signatures, it wants to be an interface.
  8. Leaking the implementation through the abstraction — one subclass that throws where another returns null, so callers must know which one they hold.

Best Practices

  • Make the base abstract as soon as instantiating it would be meaningless; let the compiler carry the rule.
  • Use abstract where there is no honest default and virtual where there is, and be able to say which applies for every member.
  • Keep the skeleton non-virtual and the holes small: one or two abstract members plus a fixed algorithm.
  • Give the abstract class a protected constructor, so it reads as "for subclasses only" even before the abstract keyword is noticed.
  • Put shared state and shared plumbing — ids, names, counters, logging — in the base with private set, so subclasses cannot falsify it.
  • Override ToString() in the base using GetType().Name or an id, and every subclass gets useful diagnostics free.
  • Write the abstraction so that callers cannot tell which subclass they hold; if they must know, the abstraction is not finished.
  • Reach for an interface instead when the types are unrelated, when there is no shared state, or when implementers already have a base class.

Practice Exercises

  1. Write an abstract Shape with an abstract double Area(), a virtual string Describe() returning $"{GetType().Name} of area {Area():F2}", and concrete Circle, Square and Triangle. Prove that new Shape() will not compile by leaving it commented out with the error code beside it, then print six shapes through a Shape[].
  2. Build an abstract Exporter with a non-virtual Export(string[] rows) that writes a header, delegates each row to protected abstract string Format(string row), and writes a footer with the row count. Implement CsvExporter and MarkdownExporter, and export the same three rows through both.
  3. Take the Job runner above and add a Backup job with MaxAttempts of 5 that succeeds on attempt four, plus an AlwaysFails job. Then try to make Attempts writable from a subclass, note which error you get, and explain in two sentences why the base class keeps that setter private.
  4. Write an abstract Account with state (Balance, Id) in the base, a non-virtual Withdraw(decimal) that applies a shared overdraft check, and a protected abstract decimal Fee(decimal amount) supplied by Current, Savings and Business subclasses. Then write two sentences on what would have to change if Account were an interface instead.