Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 182 ยท Classes and Objects

Abstract Classes and Interfaces

Learn C# abstract classes and interfaces - when to use each, explicit implementation, default interface methods, static abstract members and a clear rule for choosing between them.

Sometimes you want to describe what something can do without saying how. A payment system needs to charge cards, bank transfers and wallets, but it should not care which one it is dealing with. C# gives you two tools for that: abstract classes and interfaces. Both define a contract that other types fulfil, and both let you write code against the contract so new implementations plug in without changes. They differ in what else they can carry and in how many of them a type can use.

This lesson shows both, then goes deeper into the interface features that appear in modern C#: explicit implementation, default interface methods and static abstract members. It ends with a practical rule for choosing between them, because this decision shapes many designs.

Abstract classes: a partly finished base

An abstract class is a class that cannot be instantiated directly. It can contain normal members (fields, constructors, implemented methods) and abstract members that have no body and must be implemented by concrete subclasses. It is the right tool when related classes share real code and each has to fill in some gaps.

C# An abstract base class with shared code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Pay is the template method: it holds the fixed algorithm and calls the abstract steps. The subclasses only supply the varying parts, so the logging rule exists in one place. Trying to write new PaymentMethod() fails with error CS0144: Cannot create an instance of the abstract type or interface 'PaymentMethod'.

An abstract class may implement an interface, may have constructors (called by subclasses via base(...)), may hold state, and may mix abstract and non-abstract members. A class can inherit from only one abstract (or any other) class.

Interfaces: a pure contract

An interface lists members a type promises to provide. Names conventionally start with I. A class (or struct) can implement any number of interfaces, and unrelated classes can implement the same one, so interfaces are the main tool for flexible, testable designs.

C# One interface, unrelated implementers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Invoice and Photo have nothing in common except being printable, which is exactly the situation interfaces are for. Interface members are implicitly public; the implementing member must be public too (unless implemented explicitly, below).

Multiple interfaces and interface inheritance

A type lists its interfaces after any base class, separated by commas. Interfaces can inherit from other interfaces:

C# Combining interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Callers should depend on the smallest interface they need. A method that only reads should accept IReadable, not IWritable or Document. Small, focused interfaces are easier to implement and to fake in tests.

Explicit interface implementation

When two interfaces declare the same member name, or you want a member available only through the interface, implement it explicitly: no access modifier, and the interface name in front.

C# Explicit implementation resolves a name clash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Explicit members are private to the class: robot.Run() picks the public one, and the explicit ones are reachable only through a variable of the interface type. Explicit implementation is also handy to hide rarely used members from the class's normal surface, as .NET's collections do.

Default interface methods (C# 8)

Interfaces may provide a default implementation. It lets you add a member to an existing interface without breaking every implementer, which is why the feature exists.

C# A default interface method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A default method is reachable only through the interface type: new ConsoleLogger().LogError("x") does not compile, because ConsoleLogger itself has no LogError member (error CS1061: 'ConsoleLogger' does not contain a definition for 'LogError'). That surprises beginners. Default interface methods are best used to evolve published interfaces and to share small helper behavior; they are not a replacement for abstract classes, because interfaces still cannot have instance fields.

static abstract members (C# 11)

Interfaces can require static members, abstract in the interface and implemented by the type. Together with generics, this lets generic code call T.Create() or use T.Zero, which was impossible before. It is how generic math (INumber<T>) is built; see Generic Math.

C# A static abstract interface member

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The pattern IAnimal<TSelf> where TSelf : IAnimal<TSelf> (the "curiously recurring" pattern) lets the interface mention the implementing type. You rarely write this yourself, but you will use it through the framework's generic math interfaces.

Abstract class or interface?

Both give you polymorphism. Use this checklist:

Question Abstract class Interface
Can a type use several? No, one base class Yes, any number
Can it hold instance state (fields)? Yes No
Can it have constructors? Yes No
Shared implementation Natural Possible via default methods, but limited
Works for structs? No (structs cannot inherit classes) Yes
Adding a member later Safe if non-abstract Safe only with a default body
Typical meaning "is a kind of" with shared code "can do" or "behaves like"

A rule of thumb that holds up well in practice:

  1. Start with an interface when you only need a contract, when unrelated types will implement it, or when you want test fakes. Most dependencies in application code are interfaces (see Dependency Injection).
  2. Use an abstract class when subclasses are closely related and share state or substantial code, and you want a template method that enforces an algorithm.
  3. Use both when you want the contract plus a convenient starting point: expose IParser, and offer ParserBase : IParser that implements the boring parts. Callers depend on the interface; implementers can choose to derive from the base.

Don't create an interface for every class "just in case". An interface with one implementation and no test or plug-in need is extra code to maintain. Create it when a second implementation, a fake or a boundary between modules actually appears.

Common mistakes

  • Giant interfaces. Many unrelated methods force implementers to write stubs that throw NotImplementedException. Split them (the Interface Segregation Principle).
  • Abstract classes as a code-sharing hack. If subclasses are not really kinds of the base, use composition: Inheritance explains the trade-off.
  • Forgetting override. Implementing an abstract method needs override; implementing an interface method does not use it.
  • Expecting default methods on the class. They are visible through the interface type only.
  • Public mutable state in the base class. Keep fields private and expose protected methods; see Access Modifiers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many classes (abstract or not) can a C# class inherit from, and how many interfaces can it implement?

    C# has single inheritance for classes but a type can implement as many interfaces as it wants.
  2. 2. Which of these can an abstract class have but an interface cannot?

    Interfaces have no instance state or constructors. Since C# 8 they may have method bodies (default interface methods), and they can declare properties and abstract members.
  3. 3. A class implements an interface method explicitly. How do you call it?

    Explicit implementations are not part of the class's public surface; you reach them via the interface type, for example ((IAthlete)robot).Run().
  4. 4. What does a default interface method let you do?

    A default implementation is used by types that do not provide their own, so existing implementers keep compiling when the interface grows.
  5. 5. Which design is best when unrelated types such as Invoice and Photo must both be printable?

    Unrelated types share a capability, not an ancestry, so an interface fits better than a common base class.

Summary

  • An abstract class is a partly finished base that may hold state, constructors, implemented methods and abstract members; a class can have only one base.
  • An interface is a contract of capabilities; a type may implement many, and structs can too.
  • Explicit implementation resolves name clashes and hides members behind the interface type.
  • Default interface methods (C# 8) let interfaces grow; static abstract members (C# 11) power generic math.
  • Default to interfaces for contracts; use abstract classes for closely related types with shared code; combine both when helpful.

Next: The object Class: Equals, GetHashCode and ToString