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?