Adding functionality to interfaces with extension methods

When building large scale applications a very useful design pattern to adopt is dependency injection. An example of this is programming to interfaces such that the implementation of each interface can be interchanged.

In this post I will demonstrate some examples of how you can go about adding functionality to interfaces with extension methods.

Consider the following example with some demo interfaces and classes:

This is all well and good – the user can write log entries with the following line:

So, how can we achieve:

The interface cannot contain any implementation. One solution would be to use abstract classes for the base class however that goes against the principal of programming to interfaces.

How about extension methods? Using the following examples we can add these shorthand methods to our ILog hiding some of the complexity / repeated code:

If you setup the extension methods in the same namespace as your interface, you will now have available:

Leave a Reply

Your email address will not be published.