There's a reminder that I need from time to time. Here, I'll share it with you: it is not possible to attach an interface to a class in C#. If the class does not declare that it implements the interface, then you have no way to attach that interface or its methods to an instance of the class. This is annoying when you're trying to program to an interface and realize For example, suppose we've defined the following interface and a couple classes:
This is a toy example, so the interface isn't really that useful. However, what if I want to treat ExplicitAdder and ImplicitAdder the same way? Both classes provide an Add method that accepts two integers and returns void. They're still different types, however, and ImplicitAdder doesn't declare that it implements IAdd even though the method signature matches the definition. This is by design, of course; it could be that the method in ImplicitAdder has nothing to do with IAdd and only matches the signature by accident. But it does make things difficult when you really want that class to implement IAdd:
This code shows the result of two different types of casting in an attempt to "attach" the IAdd interface to ImplicitAdder. Of course, casting ExplicitAdder to a variable of type IAdd works just fine. But when we use the 'as' keyword to perform the same conversion on ImplicitAdder, a null value is returned, indicating that this is an invalid cast. The explicit cast throws an InvalidCastException.
It is possible to execute the Add method using reflection on the type (or in C# 4, using the dynamic type), but this makes code fragile. What if the interface changes? The compiler cant' tell us to update the class. What if the class changes? The compiler can't tell us to update the reflection code. It just moves the problem into the run-time arena. This is a tactic to use when there's no other solution, but I don't like it much for software maintenance. No, the proper way to attach an interface to a class is by using a decorator of sorts:
Here we wrap the ImplicitAdder in a class that does implement IAdd. We pass a reference to an ImplicitAdder into the constructor and then use the wrapper object instead. This way the compiler can check all of our references at compile-time due to static typing.