tags:

views:

279

answers:

2

I have method in Class which is implementation of Interface. When I made it Explicit implementation I got compiler error

The modifier 'public' is not valid for this item

Why it is not allowed to have public for explicit interface implementation ?

+7  A: 

The reason for an explicit interface implementation is to avoid name collisions with the end result being that the object must be explicitly cast to that interface before calling those methods.

You can think of these methods not as being public on the class, but being tied directly to the interface. There is no reason to specify public/private/protected since it will always be public as interfaces cannot have non-public members.

(Microsoft has an overview on explicit interface implementation)

Richard Szalay
+4  A: 

Most people don't agree with me, but I think explict member implementation allow disambiguation of interface members with the same signature.

Without explict interface member implementations it would be impossible for a class or a structure to have different implementations of interface members with the same signature and return type.

Why Explicit Implementation of a Interface can not be public? When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface.

public interface IPrinter
{
   void Print();
}
public interface IScreen
{
   void Print();
}

public class Document : IScreen,IPrinter
{
    void IScreen.Print() { ...}
    void IPrinter.Print() { ...} 
}

.....
Document d=new Document();
IScreen i=d;
IPrinter p=d;
i.Print();
p.Print();
.....

Explict interface member implementations are not accessible through class or struct instances.

adatapost
I know it can not be accessd through class instance, your answer actually made me confused, it is like we can access private methods of a class through its object LOL!!!
Prashant
Most people don't agree with you? I find that hard to believe, considering that's exactly why explicit interface implementations exist. http://msdn.microsoft.com/en-us/library/ms173157.aspx
Richard Szalay