Interfaces versus abstract classes

1 min read
On trails:CSOOPstep 6/6

Interfaces establish a contract and enable polymorphism. Abstract classes define base classes that cannot be instantiated but can be inherited, providing a blueprint for derived classes.

Interfaces

An interface defines a contract: a set of public members (methods, properties, events, indexers) that a class or struct implementing the interface must provide. An interface itself doesn’t provide any implementation. A class or struct can implement multiple interfaces, which enables a form of multiple inheritance of type. Interface members are implicitly public. Before C# 8.0 they could not contain implementation, and C# 8.0 introduced default interface methods.

Abstract classes

An abstract class provides a common base for a group of related classes. It can contain both abstract members (which derived classes must implement) and concrete members (with implementation that derived classes inherit). An abstract class cannot be instantiated directly. A class can inherit from only one abstract class (or any concrete class).

When to use which

  • Use an interface when you want to define a “can-do” relationship, or a contract that diverse, unrelated classes can fulfill. For example, IEnumerable<T> defines that a class can be enumerated. Interfaces are excellent for achieving loose coupling, and they are fundamental to patterns like Dependency InjectionDependency injection and service lifetimesHow ASP.NET Core hands each class what it needs, and how long each instance lives.Opens in a new tab. They also make code easier to test, because dependencies can be mocked easily.
  • Use an abstract class when you want an “is-a” relationship and some common, shared functionality or default behavior for a hierarchy of closely related classes. For example, a Shape abstract class might provide a concrete Color property and an abstract CalculateArea() method.

The idea behind both is in the abstraction noteAbstractionExpose what an object does, and hide how it does it.Opens in a new tab.

Where interfaces and abstract classes sit next to classes, structs and records is in choosing a typeChoosing a typeClass, struct, interface, record class or record struct.Opens in a new tab.


Sources