Reputation: 59150
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?
Upvotes: 7
Views: 296
Reputation: 4129
if you are implementing an interface to a class then the methods in interface must be there in class and all methods should be public also.
class InterfaceImplementer : IMyInterface
{
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
and you can call the method like this
IMyInterface _IMyInterface = new InterfaceImplementer();
IMyInterface.MethodToImplement();
Upvotes: 0
Reputation: 64467
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.
Upvotes: 1
Reputation: 887195
By implementing an interface explicitly, you're creating a private method that can only be called by casting to the interface.
Upvotes: 6