C # interface question

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 not visible from the outside. But if I make the following changes:

 // InterfaceImplementer.cs class InterfaceImplementer : IMyInterface { public void MethodToImplement() { Console.WriteLine("MethodToImplement() called."); } } 

Then Main.cs also compiles fine. Why is there a difference between the two?

+7
source share
3 answers

By explicitly implementing the interface , you create a private method that can only be called by casting to the interface.

+6
source

The difference is in supporting a situation where an interface method collides with another method. The idea of ​​"Explicit interface implementations" is proposed.

Your first attempt is an explicit implementation that requires direct work with a link to the interface (and not a link to what the interface implements).

The second attempt is an implicit implementation, which also allows you to work with the type of implementation.

To see explicit interface methods, follow these steps:

 MyType t = new MyType(); IMyInterface i = (IMyInterface)tiCallExplicitMethod(); // Finds CallExplicitMethod 

If you have the following:

 IMyOtherInterface oi = (MyOtherInterface)t; oi.CallExplicitMethod(); 

The type system can find the appropriate methods for the correct type without collision.

+1
source

if you are implementing an interface for a class, then the methods in the interface must be in the class, and all methods must also be public.

 class InterfaceImplementer : IMyInterface { public void MethodToImplement() { Console.WriteLine("MethodToImplement() called."); } } 

and you can call a method like this

 IMyInterface _IMyInterface = new InterfaceImplementer(); IMyInterface.MethodToImplement(); 
0
source

All Articles