I have the following code:
// IMyInterface.cs
namespace InterfaceNamespace
{
interface IMyInterface
{
void MethodToImplement();
}
}
.
// InterfaceImplementer.cs
class InterfaceImplementer : IMyInterface
{
void IMyInterface.MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
This code compiles just fine(why?). However when I try to use it:
// Main.cs
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
I get:
InterfaceImplementer does not contain a definition for 'MethodToImplement'
i.e. MethodToImplement
is not visible from outside. But if I do the following changes:
// InterfaceImplementer.cs
class InterfaceImplementer : IMyInterface
{
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
Then Main.cs also compiles fine. Why there is a difference between those two?
By implementing an interface explicitly, you're creating a private method that can only be called by casting to the interface.
The difference is to support the situation where an interface method clashes with another method. The idea of "Explicit Interface Implementations" was introduced.
Your first attempt is the explicit implementation, which requires working directly with an interface reference (not to a reference of something that implements the interface).
Your second attempt is the implicit implementation, which allows you to work with the implementing type as well.
To see explicit interface methods, you do the following:
MyType t = new MyType();
IMyInterface i = (IMyInterface)t.
i.CallExplicitMethod(); // Finds CallExplicitMethod
Should you then have the following:
IMyOtherInterface oi = (MyOtherInterface)t;
oi.CallExplicitMethod();
The type system can find the relevant methods on the correct type without clashing.
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