Codementor Events

How To Choose Between An Abstract Class and an Interface in C#

Published Jan 22, 2018

When starting out my .NET programming career, one of the things I found hard to understand and make a decision on was when to use an abstract class vs an interface. In the write up that follows, I attempt to make that distinction clear to anyone who might also find themselves in the same dilemma or just curious to know what I think.
Kindly note that the concept might be universal across other frameworks and ecosystem but my thinking is relative to .NET.

Here goes...

First, we have to understand what the two of them are; an abstract class is used to define something that conceptually represents a group of things that can be classified together due to similar attributes or behaviour common among them but itself is generic and can e.g shape, animal e.t.c
An interface on the other hand represents a trait or behaviour that any type can exhibit. E.g a shape can be "drawable", a set can be "enumerable", a class you define can be a "data table" (here, the data table is a trait).

Abstract classes form the base of a hierarchy naturally from which more specific or sub abstract classes derive. E.g A peacock is a "bird" which in turn is an "animal". Here the "bird" would be an abstract class derived from another abstract class "animal".

Use abstract classes when:

  1. A hierarchy of types that stem from universal base type exhibit similar behaviours or traits unique to only types of that hierarchy.
  2. Each type in the hierarchy has its own implementation of a generic behaviour which itself should be marked as abstract in the base class.

Use an Interface when:

  1. The trait of behaviour is not specific to any group of types or hierarchy but can be implemented by any type.
  2. The intention is to expose a particular trait or behaviour to all types.
Discover and read more posts from Oswald Umeh
get started
post commentsBe the first to share your opinion
Show more replies