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.