Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 526
Caner Avatar asked May 18 '11 11:05

Caner


2 Answers

By implementing an interface explicitly, you're creating a private method that can only be called by casting to the interface.

like image 168
SLaks Avatar answered Nov 01 '22 04:11

SLaks


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.

like image 1
Adam Houldsworth Avatar answered Nov 01 '22 04:11

Adam Houldsworth