Search code examples
c#interfaceexplicit-implementation

How does one choose whether to implement an interface or explicitly implement an interface?


There are two ways to implement an interface:

interface IMyInterface
{
    void Foo();
}

class IImplementAnInterface : IMyInterface
{
    public void Foo()
    {
    }
}
// var foo = new IImplementAnInterface();
// foo.Foo(); //Ok
// ((IMyInterface)foo).Foo(); //Ok

class IExplicitlyImplementAnInterface : IMyInterface
{
    void IMyInterface.Foo()
    {
    }
}
// var foo = new IExplicitlyImplementAnInterface();
// foo.Foo(); //ERROR!
// ((IMyInterface)foo).Foo(); //Ok

The difference is that if the interface is explicitly implemented, it must actually be cast as the given interface before someone's allowed to call the Foo method.

How does one decide which to use?


Solution

  • If there are collisions (two interfaces have a method with the same signature, or your class/base class and an interface collide the same way), and you don't want the colliding methods to have the same bodies, then you have to use explicit interfaces.

    Otherwise, you are free to choose. If you want to hide some implemented methods, you choose the explicit method. For example, the Dictionary<,> class does it with some methods of the ICollection<> interface, because the hidden methods would confuse people.