Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Explicit Implementation of a Interface can not be public?

Tags:

c#

interface

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 ?

like image 901
Prashant Cholachagudda Avatar asked Aug 10 '09 05:08

Prashant Cholachagudda


People also ask

CAN interfaces have public methods?

The Interface BodyAll abstract, default, and static methods in an interface are implicitly public , so you can omit the public modifier. In addition, an interface can contain constant declarations. All constant values defined in an interface are implicitly public , static , and final .

Does not implement interface member because it is not public?

The error thrown is usually “Cannot implement an interface member because it is not public”. If an interface member method is implemented in your class without an access modifier, it is by default private. To change the visibility, you can either change the interface from public to internal.

What is implicit and explicit implementation of interface?

Resolving conflicts here ..... "Implicit Implementation" - means just simple implementation of a particular method having same name and same signature which belongs to the same class itself, where as "Explicit Implementation" - means implementation of a method using their Interface name having same name and signature ...

Why are interface members public by default?

1) Interface members are only visible to code outside of the interface based on the rules of the respective visibility level. public : Interface members in C# are public by default, so this works.


1 Answers

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)

like image 171
Richard Szalay Avatar answered Sep 22 '22 06:09

Richard Szalay