Tutorials / Advanced C# and .NET / Interfaces and abstract classes

Interfaces and abstract classes

14 min read csharp
Course contents (16 lessons)
  1. The type system
  2. Records, structs and value equality
  3. Interfaces and abstract classes
  4. Generics and constraints
  5. Delegates, events and lambdas
  6. Querying and matching data
  7. LINQ in depth: deferred execution, grouping and joins
  8. IEnumerable versus IQueryable
  9. Pattern matching in modern C#
  10. Async and await: how Task really works
  11. Async patterns: cancellation, timeouts and async streams
  12. Application structure
  13. Dependency injection and service lifetimes
  14. Configuration, options and logging
  15. Data and web
  16. Entity Framework Core basics: DbContext, migrations and queries
  17. Building a minimal API with ASP.NET Core
  18. Unit testing with xunit
  19. Performance and the final project
  20. Performance basics: Span of T and fewer allocations
  21. Final project: a notes API with EF Core, DI and logging

Programming to a contract

Suppose your app sends notifications. Today it sends email. Next month the business wants SMS. If every piece of code calls an EmailSender class directly, you must change them all. If the code depends on a small contract that says "something that can send a message", you add a new class and change one line where the objects are created.

That contract is an interface. It lists members with no implementation. Any class that implements the interface promises to supply them.

Interface versus abstract class

An abstract class is a partly finished class. It can contain fields, constructors, working methods and abstract methods that subclasses must fill in. A class can inherit from only one base class, but it can implement many interfaces.

  • Use an interface to describe a capability that unrelated classes can share: IDisposable, IComparable, INotifier.
  • Use an abstract class when several related classes share real code and state, and you want to enforce a step they must each supply.
var notifiers = new List<INotifier>
{
    new EmailNotifier("noreply@example.com"),
    new SmsNotifier("+92300000000"),
    new ConsoleNotifier()
};

foreach (INotifier n in notifiers)
{
    n.Send("sara@example.com", "Your order has shipped.");
}

Console.WriteLine();

var reports = new Report[] { new SalesReport(), new InventoryReport() };
foreach (Report r in reports)
{
    r.Run();
}

interface INotifier
{
    string Name { get; }
    void Send(string to, string message);

    // Default implementation: callers get it for free
    void SendMany(IEnumerable<string> recipients, string message)
    {
        foreach (string r in recipients) Send(r, message);
    }
}

class EmailNotifier(string from) : INotifier
{
    public string Name => "Email";
    public void Send(string to, string message) =>
        Console.WriteLine($"[{Name}] from {from} to {to}: {message}");
}

class SmsNotifier(string sender) : INotifier
{
    public string Name => "SMS";
    public void Send(string to, string message) =>
        Console.WriteLine($"[{Name}] from {sender} to {to}: {message}");
}

class ConsoleNotifier : INotifier
{
    public string Name => "Console";
    public void Send(string to, string message) =>
        Console.WriteLine($"[{Name}] {to} - {message}");
}

abstract class Report
{
    // The algorithm is fixed here; subclasses fill in the steps.
    public void Run()
    {
        Console.WriteLine($"=== {Title} ===");
        foreach (string line in BuildLines())
        {
            Console.WriteLine(line);
        }
        Console.WriteLine($"Generated at {DateTime.Now:HH:mm}");
        Console.WriteLine();
    }

    protected abstract string Title { get; }
    protected abstract IEnumerable<string> BuildLines();
}

class SalesReport : Report
{
    protected override string Title => "Sales";
    protected override IEnumerable<string> BuildLines()
    {
        yield return "Online: 120 orders";
        yield return "Store: 45 orders";
    }
}

class InventoryReport : Report
{
    protected override string Title => "Inventory";
    protected override IEnumerable<string> BuildLines()
    {
        yield return "Notebooks: 340";
        yield return "Pens: 1,200";
    }
}

Walking through it

The list is typed as List<INotifier>. The loop does not know or care which class each item is. It calls Send, and the correct version runs. This is polymorphism: one call, many behaviours chosen at runtime. To add Telegram support, I write one new class and add it to the list. The loop stays as it is.

The classes use primary constructors: class EmailNotifier(string from). The parameter is available inside the class body. It is a handy way to cut boilerplate. Note that the parameters are not properties, and you cannot read them from outside.

The interface has a default method, SendMany. It is available on any implementer without extra code. Use this sparingly. It is meant for evolving an existing interface without breaking old classes. If you reach for it all the time, an abstract class may be the better design.

The Report class shows the template method pattern. The abstract base class owns the order of steps in Run. Subclasses supply only the title and the lines. Because Run is not virtual, subclasses cannot change the order by accident. The protected abstract members must be overridden, or the code does not compile. The yield return statements build a sequence one item at a time. You will see more of that in the LINQ lessons.

Do not over-engineer

I have seen codebases where every class has an interface with one implementation, "just in case". That adds files and noise and no value. Create an interface when you have two real implementations, or when you need to replace something in tests, such as a clock, an email service or a payment gateway. If neither is true, wait.

Common mistakes

  • Deep inheritance trees. Prefer composition: give a class a field of the type it needs instead of inheriting from it.
  • Forgetting virtual. A method can be overridden only if the base declares it virtual or abstract.
  • Interfaces with too many members. A fat interface forces implementers to write methods they do not need. Split it.
  • Calling a virtual method from a constructor. The subclass part is not yet built, so the override may see empty fields.

Try it yourself

  1. Add an IDiscount interface with a method decimal Apply(decimal price). Write PercentageDiscount and FixedDiscount classes.
  2. Write a method that takes a price and a list of discounts and applies them in order.
  3. Write an abstract class Shape with an abstract Area() and a concrete Describe() that prints the area. Add Circle and Rectangle.
csharp
var notifiers = new List<INotifier>
{
    new EmailNotifier("noreply@example.com"),
    new SmsNotifier("+92300000000"),
    new ConsoleNotifier()
};

foreach (INotifier n in notifiers)
{
    n.Send("sara@example.com", "Your order has shipped.");
}

Console.WriteLine();

var reports = new Report[] { new SalesReport(), new InventoryReport() };
foreach (Report r in reports)
{
    r.Run();
}

interface INotifier
{
    string Name { get; }
    void Send(string to, string message);

    // Default implementation: callers get it for free
    void SendMany(IEnumerable<string> recipients, string message)
    {
        foreach (string r in recipients) Send(r, message);
    }
}

class EmailNotifier(string from) : INotifier
{
    public string Name => "Email";
    public void Send(string to, string message) =>
        Console.WriteLine($"[{Name}] from {from} to {to}: {message}");
}

class SmsNotifier(string sender) : INotifier
{
    public string Name => "SMS";
    public void Send(string to, string message) =>
        Console.WriteLine($"[{Name}] from {sender} to {to}: {message}");
}

class ConsoleNotifier : INotifier
{
    public string Name => "Console";
    public void Send(string to, string message) =>
        Console.WriteLine($"[{Name}] {to} - {message}");
}

abstract class Report
{
    // The algorithm is fixed here; subclasses fill in the steps.
    public void Run()
    {
        Console.WriteLine($"=== {Title} ===");
        foreach (string line in BuildLines())
        {
            Console.WriteLine(line);
        }
        Console.WriteLine($"Generated at {DateTime.Now:HH:mm}");
        Console.WriteLine();
    }

    protected abstract string Title { get; }
    protected abstract IEnumerable<string> BuildLines();
}

class SalesReport : Report
{
    protected override string Title => "Sales";
    protected override IEnumerable<string> BuildLines()
    {
        yield return "Online: 120 orders";
        yield return "Store: 45 orders";
    }
}

class InventoryReport : Report
{
    protected override string Title => "Inventory";
    protected override IEnumerable<string> BuildLines()
    {
        yield return "Notebooks: 340";
        yield return "Pens: 1,200";
    }
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account