views:

167

answers:

2

I just started figuring out the difference between implicit and explicit interface implmentation in .Net. Since I come from a Java background the idea is still a bit confusing. I am hoping knowing which Java does will make it more obvious what the difference is. I am assuming the Java is explicit???

+3  A: 

Nope Java is implicit. Explicit is where you are implementing multiple interfaces that have the same method signatures in them and you explicitly state which interface the implementation is for.

An example from MSDN:

public class SampleClass : IControl, ISurface
{
    void IControl.Paint()
    {
        System.Console.WriteLine("IControl.Paint");
    }
    void ISurface.Paint()
    {
        System.Console.WriteLine("ISurface.Paint");
    }
}

Here we have two Paint() methods, one from each interface. In Java you can only have one Paint() implementation. In C# you have the option of implementing versions for each interface so you get different behaviour depending how the class is called.

So if I called:

SampleClass c = new SampleClass();
((IControl)c).Paint();
((ISurface)c).Paint();

I'd get "IControl.Paint" printed out followed by "ISurface.Paint" printed out.

Paolo
Okay that makes sense I guess. In Java I would just create a new interface to get around this problem.
uriDium
Maybe another question then. I am trying to create an implementation of IDictionary(Of TKey, TValue). Are you saying that I should explicit implement all the IDictionary and rather implicit implement the others that come from ICollection and IEnumerable?
uriDium
Generally the answer is no, unless you *really* need to have different behaviours for the different interfaces (and there had better be a damn good for that reason too) I would avoid using the explicit style. IDictionary already extends ICollection and IEnumerable so you don't need to implement these separately, just implement IDictionary.
Paolo
+1  A: 

In Java there is no distinction between explicit and implicit. If you have two interfaces that both declare a method with the same signature, and a class that implements both interface, then a method in the class with the correct signature implements the method in BOTH interfaces.

Stephen C
Okay. Then you cannot cast to either of the interfaces and use that particular version of the method. The version that you have is the only version and satisfies both interfaces?
uriDium
@uriDium - Yes, this is correct
Paolo
@uriDium - yes.
Stephen C