I recently bought a book by Juval Lowy: .Net Components.
Been brushing up on my knowledge on the use of interfaces. Of course I know the basics, but in the book I stumbled upon explicit implemented interfaces.
I already aksed some of my collegues why sometime interfaces where just implemented by methodname and sometimes the interfacename was mentioned.
Like:
void Method1 vs. void IMyInterface.Method1
None of my collegues knew the answer (or maybe I asked the wrong guys...).
So let's have an example:
public interface IMyInterface
{
void Method1();
void Method2();
}
public class MyClass : IMyInterface
{
public void Method1(){...}
void IMyInterface.Method2(){...}
}
As you can see Method1 is an implementation of the interface an can be used like this:
MyClass obj = new MyClass();
obj.Method1();
But because Method2 is explicitly implemented, you cannot reach Method2 in this case. You need to use the interface to reach Method2, like this:
IMyInterface obj;
obj = new MyClass();
obj.Method2();
So there you go, another mystery solved...
If you want to prevent a client from directly accessing the interface methods without using the interface, use an explicitly implemented interface.
Cheers.
P.S. I forgot to mention that you also implement explicit interfaces when you want to avoid collisions between identical method names from different interfaces. But that's abvious, isn't it...