Question

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?

Was it helpful?

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.

OTHER TIPS

There are cases where you have to provide an explicit implementation for example when implementing IEnumerable and IEnumerable<> where both interfaces expose a GetEnumerator method.

One general rule I follow is if I implement an interface but provide additional more convient and typesafe methods and properties to expose the interface functionality, I would exlicitly implement the interface. This makes public interface the class exposes more appropriate, while still allowing algorithms that might rely on the implemented interface to access the interface provided methods and properties.

That was hard to word, but I hope it makes some sense.

I would only recommend this in cases where multiple interfaces are being implemented, and they both contain a method of the same name.

You can also explicitly implement a method to effectively "hide" it and implement an equivalent method with a better name. System.IO.Stream does this, implementing Dispose explicitly and providing the better-named Close().

See this MSDN article for more: http://msdn.microsoft.com/en-us/library/ms229034.aspx.

It's most commonly seen as a workaround for .NET forbidding "return type covariance".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top