Explicit Interface Usage in C#

Where possible, I try and program against interfaces as much as possible. I do this because I like Interface-based programming and because I like the characteristics that it brings to the table: reusability, maintainability, and extensibility. It also allows you to effectively test your code using Mocks.

Whether or not you like to code this way, you may however find that there are certain situations in which you need to explicitly set the usage of an interface. When working in a team of developers it is possible that a method on a class could be called using the concrete class instead of an interface. This would break the general interface based concept as a whole and it would also make it a lot harder to find at a later stage.

Now there is a quick way to get around this, however it still needs to be enforced as a coding style. Let's say we have the following Interface:


Normally, we would call it like this:


Instead, if we call it like this:

Interface Implementation

It now forces the next person to call the method to do so from the interface. If they try to call the concrete class the following error should occur.

Interface Error

But when called correctly:


It's also not too late to do this change to an existing project, it will show up all the concrete classes that have been called.

For some further reading, please check out this link on MSDN and this one for a tutorial on MSDN