Why Explicit Implementation of a Interface can not be public?

C#Interface

C# Problem Overview


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 ?

C# Solutions


Solution 1 - C#

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)

Solution 2 - C#

The 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPrashant CholachaguddaView Question on Stackoverflow
Solution 1 - C#Richard SzalayView Answer on Stackoverflow
Solution 2 - C#KV PrajapatiView Answer on Stackoverflow