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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With