Abstract classes

An abstract class

An abstract class is a base class that cannot be instantiated: it exists to be derived from. An abstract member has no body, so every non-abstract subclass must provide one with override, and the compiler checks that none was forgotten.

Shape[] shapes = { new Circle(2), new Square(3) }; foreach (var shape in shapes) { Console.WriteLine(shape.Report()); } Console.WriteLine($"shapes: {shapes.Length}"); abstract class Shape { public abstract double Area { get; } public abstract string Name { get; } public string Report() => $"{Name} area {Area:F2}"; } class Circle(double radius) : Shape { public override string Name => "circle"; public override double Area => Math.PI * radius * radius; } class Square(double side) : Shape { public override string Name => "square"; public override double Area => side * side; }

dotnet run

circle area 12.57
square area 9.00
shapes: 2

The array is an array of Shape, and only the two concrete subclasses can be put in it. Report is written once and calls the two abstract properties, which each subclass fills in: that is the shape of a template method, and it is the main reason to make a base class abstract.

A template method

A template method is a concrete method in the base class that calls abstract or virtual members, so the order and the shared part live in one place and the part that differs lives in each subclass. The hook here is protected abstract, which keeps it out of the public surface:

var log = new TimestampedLog("app"); log.Write("started"); log.Write("ready"); Console.WriteLine(log.Text); abstract class Log { private readonly List<string> lines = new(); public string Text => string.Join(Environment.NewLine, lines); public void Write(string message) => lines.Add(Format(message)); protected abstract string Format(string message); } class TimestampedLog(string name) : Log { protected override string Format(string message) => $"{name}: {message}"; }

dotnet run

app: started
app: ready

Write is public and cannot be overridden; it owns the list of lines and the order they go in. A subclass can only change the formatting, which is the one decision that belongs to it. When a later change needs a timestamp on every line, it goes into Write once and every subclass gets it.

The error of new on an abstract type

An abstract class has no complete implementation, so the runtime refuses to build an object from it. The compiler catches the attempt first:

var shape = new Shape(); Console.WriteLine(shape.Name); abstract class Shape { public abstract string Name { get; } }

dotnet build

Program.cs(1,13): error CS0144: Cannot create an instance of the abstract type or interface 'Shape'

Build FAILED.

Program.cs(1,13): error CS0144: Cannot create an instance of the abstract type or interface 'Shape'
0 Warning(s)
1 Error(s)

Time Elapsed 00:00:05.53

The message names both cases, an abstract type and an interface, because the rule is the same for both: what is missing is an implementation of at least one member. The fix is a concrete class that derives from it, not a cast or a factory.

Interface or abstract class

Both describe a contract and both can be used as the type of a variable. The difference is what each may carry:

The rule of this course: an interface for a capability that several unrelated types provide, an abstract class when the subclasses share code or state. The next lessons on interfaces show the other side.

Exercises

  1. Add a Triangle to the shape program with three sides and compute its area with Heron formula.
  2. Add a concrete method to Shape that returns whether the area is above a limit, and use it on both shapes.
  3. Derive a class from Shape without overriding Name and read the error.
  4. Give Log a second abstract member and a subclass that leaves it out.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What can an abstract class not do?

    Answer

    Be instantiated with new

    It is incomplete by definition, so only its concrete subclasses can be created.

  2. What must a concrete subclass of an abstract class do with its abstract members?

    Answer

    Override every one of them

    The compiler reports a missing override as CS0534 before the program can run.

  3. What does this program print? Shape s = new Square(2); Console.WriteLine(s.Area); abstract class Shape { public abstract double Area { get; } } class Square(double side) : Shape { public override double Area => side * side; }

    Answer

    4

    The override computes two squared, which is 4.

  4. What is a template method?

    Answer

    A concrete base method that calls abstract or virtual members

    It fixes the shared sequence of steps and leaves the differing ones to subclasses.

  5. What does CS0144 report?

    Answer

    An instance of an abstract type or an interface was created

    The error names the abstract type that cannot be instantiated.

  6. Which member may an abstract class have that an interface may not?

    Answer

    An instance field

    An interface stores no instance state, so a field belongs to the abstract class.

  7. What does this program print? var log = new L(); log.Write("a"); Console.WriteLine(log.Text); abstract class B { private string text = ""; public string Text => text; public void Write(string m) => text += Format(m); protected abstract string Format(string m); } class L : B { protected override string Format(string m) => m.ToUpperInvariant(); }

    Answer

    A

    The template method calls the override, which upper-cases the message.

  8. How many abstract base classes may a class have?

    Answer

    One, like any base class

    C# allows one base class, abstract or not, and several interfaces.

  9. Why is a protected abstract member useful?

    Answer

    A subclass must implement it without exposing it to callers

    The base calls the hook, and no outside code can invoke it directly.

  10. Which sentence is true about an abstract class with no abstract members?

    Answer

    It still cannot be instantiated

    The abstract keyword alone forbids instantiation, whatever the members are.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev