Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 625
Billy ONeal Avatar asked Feb 26 '23 12:02

Billy ONeal


2 Answers

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.

like image 114
fejesjoco Avatar answered Apr 09 '23 03:04

fejesjoco


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.

like image 32
Chris Taylor Avatar answered Apr 09 '23 03:04

Chris Taylor