Interfaces

By: Cam Wohlfeil
Published: 2018-08-19 1630 EDT
Category: Programming
Tags: csharp

This is something I wrote up very quickly to help me better understand Interfaces in C#, particularly why you would use them instead of abstract classes. This isn't specific to C#.

So, what's the point of Interfaces? It's not just a work around for not having multiple inheritance in C#, and multiple inheritance sucks anyways so you shouldn't ever do it. Through research, I found that the interface is a contract. When you design an interface you're saying, "To provide this capability, you must implement these methods, provide these properties and indexers, and support these events." The implementer of the interface agrees to the contract and implements the required elements.

Of course, this doesn't explain WHY you'd use an interface, the more important question. It provides loose coupling and abstraction without the messiness of inheritance, though at the cost of code duplication. When using the interface, you just leave it to the concrete implementations to handle everything correctly.

This may sound like an abstract class, but they are different. An interface is meant to be mixed in with other inheritance chains. It has the implements relationship, not the is-a relationship. An interface does not have a constructor, you can't instantiate an instance of an interface.

References: