I am confused in the default access modifier for C # interface members

What is an access modifier for interface methods? It must be public or protected , because you have access to them when they are implemented (which makes sense). It should also be abstract because they have no implementation. But lately I've been reading a book called CLR Via C #, and the chapter on interfaces says the following

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

When you check interface member virtual , the compiler complains that the access modifier is invalid. I mean that no access modifier works for anything in the interface , and not the default that is given to them using compiler rights? Can anyone explain this to me?

+4
source share
2 answers

Interfaces (C # Programming Guide)

Interfaces can contain methods, properties, events, indexes, or any combination of these four types of members. For links to examples, see Related topics. An interface cannot contain constants, fields, operators, instance constructors, destructors, or types. Interface members are automatically published, and they cannot include any access modifiers. Members also cannot be static.

And about the implementation of interface elements:

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

Thus, you cannot implement a member of an interface using protected one.

+8
source

I do not agree with your comment:

The CLR requires interface methods to be marked as virtual. Unless you explicitly mark a method as virtual in your source code, the compiler marks this method as virtual and sealed.

esp because you mentioned CLR Via C #, I'm sure you read incorrectly. The Bible cannot be wrong.

Edit: providing more details.

As suggested by others, you cannot have an access modifier (or virtual) in an interface member. By default (and by definition), all members within an interface are public and abstract.

0
source

Source: https://habr.com/ru/post/1490862/


All Articles