views:

49

answers:

2

I've been having a look at explicit interface implementations in IL. The method Method in the following class (interface IA has a single Method() on it):

public class B : IA
    object IA.Method() {
        /* code */
    }
}

is compiled to the following IL method signature:

.method private hidebysig newslot virtual final instance object IA.Method() cil managed {
    .override IA::Method
    /* code */
}

My question is - why is the method name in IL IA.Method(), rather than just straight Method? What does this actually mean, and why doesn't it work if it's missed off? I can't find anything in the ECMA spec or google about it.

+3  A: 

This is because this way you can have a method multiple times.

public class B : IA
{
    object Method() {    }
    object IA.Method() {    }
}

The first is a normal method. The second is the interface implementation. Without the prefix you could not have both because you could not differentiate between them.

new B().Method(); // calls the normal method
((IA)new B()).Method(); // calls the IA interface method
codymanix
Aaah, right. I couldn't find in the spec where this syntax/behaviour is defined.
thecoop
+2  A: 

Here's the documentation you're looking for:
http://msdn.microsoft.com/en-us/library/ms173157.aspx

The reason for it is to handle this case:

public class C : IA, IB
{
    object IA.Method()
    { 
        // Implementation!
    } 
    object IB.Method()
    { 
        // Implementation!
    } 
}

If you've got two methods with the same signature that you want to implement, you need something to make them different so you can supply seperate implementations. The name of the interface provides that.

Task