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


Jag - 3/22/2011
Hey Dean... This is a neat little trick...thanks for the tip :-) Cheers---Jag

Isaac - 3/22/2011
Nice one Dean - I like that a lot.

Oleh - 3/23/2011
Hey, quite basic article.

AliC - 7/1/2011
I thought I knew the reason for explicitly defined interfaces (namely, a way to avoid clashes with similarly named methods in the same class). Now I know this reason too, and it's a far more useful one, and such a simple change too.

Add your comment

300 Characters left

Please fill this in to confirm that you are human