Explicit interface implementations (basic)

We have come across an interface example in my post Extension methods yesterday.

I am going to follow up on interfaces today.
Let’s have a look at an explicit and an implicit interface implementation:

public interface IInterfaceA {
    void MethodA();
} 
class Implicit : IInterfaceA {
    public void MethodA() { }
} 
class Explicit : IInterfaceA {
    void IInterfaceA.MethodA() { }
    //public void IInterfaceA.MethodA() { } // won't compile, cannot use the "public" modifier
} 

The class Explicit does not allow a public modifier for MethodA(). This restricts the access.
Explicit interface implementations can only be accessed by using the interface directly. In the next example the compiler will complain about lExplicit.MethodA(). The instance lExplict cannot access the method, but the interface call b.MethodA() on the same object apparently is no problem. This way explicit interface implementation is used to hide members of a class.

void Test() {
    Implicit lImplicit = new Implicit();
    lImplicit.MethodA(); // business as usual
    IInterfaceA a = lImplicit;
    a.MethodA();

    Explicit lExplicit = new Explicit();
    lExplicit.MethodA(); // compiler error
    IInterfaceA b = lExplicit;
    b.MethodA(); // works 🙂
} //

In theory we could simply write a class with an overridden modifier to have a similar behaviour. To tell you the truth right away: It won’t compile.

public class MyGeekClass : IInterfaceA {
    private void MethodA() { }  // compiler error: private modifier not allowed
}

Why does it not compile? First of all the private modifier does not exactly describe the public behavior via the interface instance.
Secondly using the private modifier would not solve naming issues. Interfaces support multiple inheritance, so the problem is a bit more tricky. Microsoft solved it in an appropriate way. Here is an example:

public interface ICat {
    void DoSomething();
}
public interface IDog {
    void DoSomething();
}
public class Animal : ICat, IDog {
    void ICat.DoSomething() { Console.WriteLine("Cat"); }
    void IDog.DoSomething() { Console.WriteLine("Dog"); }
}
static void Main(string[] args) {
    Animal lAnimal = new Animal();
    //lAnimal.DoSomething(); // compiler error
    ICat lCat = lAnimal;
    IDog lDog = lAnimal;
    lCat.DoSomething();
    lDog.DoSomething();
} //

example output:
Cat
Dog

About Bastian M.K. Ohta

Happiness only real when shared.

Posted on January 7, 2014, in Basic, C#, Interfaces and tagged , , , , , , , , . Bookmark the permalink. 1 Comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: