Interface vs Abstract Class in C#

If you are confused about the difference between an Interface and an Abstract class, you are not alone. It is a popular topic and a common dilemma for beginners. Even experienced developers may not be able to answer the question ‘When do I choose one over the other?’. After this post, however, you should be able to.

What is an Interface?

An Interface is a declaration of events, methods, and properties but not the implementation of those things. Think of it as an outline. It is directing you as to what you must do but not dictating the how to you. I also like to refer to Interfaces as contracts because that is what they are. Contracts are written or spoken agreements that are enforceable by law. By implementing an Interface, you are agreeing to implement the events, methods, and properties of that contract. Notice the terminology surrounding the Interface. Implementation is an important word. The word implements describe exactly what you do to an interface. Since the interface does not contain its own implementation, you must provide that implementation. It may also be helpful to remind you that C# does not support multiple inheritance. Since an interface is not inherited but implemented, this limitation does not have any effect on interfaces. A class can implement many different interfaces but can only inherit from a single class, abstract or otherwise.

What is an Abstract Class?

An abstract class is sometimes referred to as a base class. It cannot be instantiated so it must be inherited and it is created with the intention that it be inherited and extended. It will (usually) provide some of its own implementation but not all. The events, methods, and properties that you must implement yourself are marked as virtual. An abstract class can also be considered a contract, really. The nature of the abstract class means that it is forcing any child class that inherits from it into a specific set of rules but may also provide some implementation.

Why so confusing? Which do I choose?

On the surface, it may seem like interfaces and abstract classes are very similar and you would be right but it stops at the surface. An interface defines what you can do while an abstract class defines what you are.

Let’s look at a very simple example such as vehicles. A vehicle can be a car, a truck, a bus, or a plane. These are WHAT the objects in the hierarchy are. So, in this case, an abstract class such as AVehicle might be warranted. A vehicle might move, fly, or float. Since these are behaviors, IFly, IMove, and IFloat would all be acceptable interfaces.

The simplest way to distinguish between an interface and an abstract class is to ask that very simple question: Does it define what I do (interface) or what I am (abstract class)?

 

Leave a Reply

Your email address will not be published.