Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm confused about default access modifier of C# interface members [duplicate]

Tags:

c#

interface

clr

What is the access modifier of interface methods? It should be public or protected because you have access to them when you implement them (which makes sense). It also should be abstract because they don't have implementation. But lately I've been reading a book called CLR Via C# and the chapter about interfaces says the following

The CLR requires that interface methods be marked as virtual. If you do not explicitly mark the method as virtual in your source code, the compiler marks the method as virtual and sealed.

When you mark the interface member virtual compiler complains that the access modifier in not valid. I mean no access modifier is valid for anything in interface rather than the default one which is given to them by compiler right? Can anyone make it clear for me?

like image 205
Dimitri Avatar asked Feb 15 '23 23:02

Dimitri


1 Answers

Interfaces (C# Programming Guide)

Interfaces can contain methods, properties, events, indexers, or any combination of those four member types. For links to examples, see Related Sections. An interface can't contain constants, fields, operators, instance constructors, destructors, or types. Interface members are automatically public, and they can't include any access modifiers. Members also can't be static.

And about interface members implementation:

To implement an interface member, the corresponding member of the implementing class must be public, non-static, and have the same name and signature as the interface member.

So you can't implement an interface member using protected one.

like image 180
MarcinJuraszek Avatar answered Apr 08 '23 08:04

MarcinJuraszek