TExcelTAD
Home › C# › C# Abstraction

C# Abstraction

Abstraction means focusing on what something does and hiding how it does it. When you call list.Sort(), you do not care which sorting algorithm runs — you only care that the list ends up sorted. In C#, the main tools for abstraction are abstract classes and interfaces (next lesson).

Abstract classes

Some classes only make sense as a base for others. What would a plain "Shape" look like? It has no formula for its area until you know whether it is a circle or a rectangle. Mark such a class abstract:

  • An abstract class cannot be instantiated with new.
  • It can declare abstract members — members with no body, which every non-abstract subclass must override.
  • It can also contain normal fields, constructors, properties and fully implemented methods that subclasses inherit.
csharp · try it yourself
using System;

Shape[] shapes = { new Circle(2), new Rectangle(3, 4), new Triangle(3, 4, 5) };

foreach (Shape s in shapes)
    Console.WriteLine(s.Describe());

abstract class Shape
{
    public abstract string Name { get; }
    public abstract double Area();
    public abstract double Perimeter();

    // A concrete method that relies on the abstract ones
    public string Describe() => 
quot;{Name,-9} area={Area(),6:F2} perimeter={Perimeter(),6:F2}"; } class Circle : Shape { private readonly double r; public Circle(double radius) => r = radius; public override string Name => "Circle"; public override double Area() => Math.PI * r * r; public override double Perimeter() => 2 * Math.PI * r; } class Rectangle : Shape { private readonly double w, h; public Rectangle(double width, double height) { w = width; h = height; } public override string Name => "Rectangle"; public override double Area() => w * h; public override double Perimeter() => 2 * (w + h); } class Triangle : Shape { private readonly double a, b, c; public Triangle(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public override string Name => "Triangle"; public override double Perimeter() => a + b + c; public override double Area() { double s = Perimeter() / 2; // Heron's formula return Math.Sqrt(s * (s - a) * (s - b) * (s - c)); } }
Circle    area= 12.57  perimeter= 12.57
Rectangle area= 12.00  perimeter= 14.00
Triangle  area=  6.00  perimeter= 12.00

Describe is written once in the base class, yet it produces correct results for every shape, because it calls the abstract members that each subclass fills in.

If a subclass forgets to implement an abstract member, the program does not compile:

csharp
abstract class Shape { public abstract double Area(); }
class Blob : Shape { }      // error CS0534: 'Blob' does not implement inherited abstract member 'Shape.Area()'

var s = new Shape();         // error CS0144: Cannot create an instance of the abstract type 'Shape'

The template method pattern

Abstract classes shine when an algorithm has a fixed structure but some steps vary. The base class defines the overall flow; subclasses supply the details:

csharp · try it yourself
using System;

new CsvReport().Generate();
Console.WriteLine();
new HtmlReport().Generate();

abstract class Report
{
    private readonly string[] rows = { "Apples;3", "Pears;5" };

    public void Generate()               // the fixed algorithm
    {
        WriteHeader();
        foreach (string row in rows)
        {
            var parts = row.Split(';');
            WriteRow(parts[0], int.Parse(parts[1]));
        }
        WriteFooter();
    }

    protected abstract void WriteHeader();
    protected abstract void WriteRow(string item, int qty);
    protected virtual void WriteFooter() { }   // optional step
}

class CsvReport : Report
{
    protected override void WriteHeader() => Console.WriteLine("item,qty");
    protected override void WriteRow(string item, int qty) => Console.WriteLine(
quot;{item},{qty}"); } class HtmlReport : Report { protected override void WriteHeader() => Console.WriteLine("<table>"); protected override void WriteRow(string item, int qty) => Console.WriteLine(
quot; <tr><td>{item}</td><td>{qty}</td></tr>"); protected override void WriteFooter() => Console.WriteLine("</table>"); }
item,qty
Apples,3
Pears,5

<table>
  <tr><td>Apples</td><td>3</td></tr>
  <tr><td>Pears</td><td>5</td></tr>
</table>

Note the difference between abstract (subclasses must override) and virtual (subclasses may override; the base supplies a default).

Abstract members at a glance

Member In abstract class In subclass
public abstract void M(); No body allowed Must override (unless the subclass is abstract too)
public virtual void M() { … } Has a default body May override
public void M() { … } Has a body Inherited as-is
Constructor Allowed (called via base(...)) —

Abstraction in everyday .NET

You use abstractions constantly. Stream is an abstract class: FileStream, MemoryStream and network streams all implement Read and Write differently, but code that accepts a Stream works with all of them. Similarly, TextWriter is the abstraction behind both Console.Out and a StreamWriter writing to a file.

Tip: Choose an abstract class when related types share code and state. Choose an interface when unrelated types merely share a capability — and remember a class can implement many interfaces but inherit only one class.

Test yourself

Which statement about abstract classes is true?

  1. They cannot have constructors
  2. They cannot be instantiated directly
  3. All their methods must be abstract
  4. They cannot have fields

A non-abstract class derives from an abstract class but does not override one of its abstract methods. What happens?

  1. The method does nothing
  2. The method throws when called
  3. Compile error
  4. The base method runs

What is the difference between abstract and virtual methods?

  1. None
  2. Abstract has no body and must be overridden; virtual has a body and may be overridden
  3. Virtual has no body
  4. Abstract methods are private