Class declaration in C#

Asked

Viewed 185 times

1

What other access levels can I declare a class in C# besides public and private. I found these levels in the microsoft website:

protected
internal
protected internal
Show 1 more comment

1 answer

2


Classes can be declared as public, private, or internal implicitly if nothing is described in the code.

Contrary to what many people think a class without explicit visibility is not public, it is internal to the compilation unit, in the case to the file Assembly, so everything that is compiled together in the same executable file sees it, but other parts of the application do not, to make it public need to make it explicit.

Private class only makes sense if it is within another class which will make only this class can see it. Its usefulness is limited to some cases.

The documentation presented in the question does not speak about the visibility of classes, but of class members. Perhaps by confusing these concepts it is difficult to understand.

Actually, when I say classes I mean classes guys, I’ve used the term of the question, but anything that goes for classes goes for structures, enumerations and delegates.

If you want to know about member visibility the question is not exactly duplicate because C# is a little different.

There are in addition to the described public members (public) that are seen by every application but with scope of the type or instance of that type.

Has the private members (private) which are only seen inside the type, whether static or not.

The protected member (protected) already known as the private, but also lets the inherited classes of this class see this member. Note that only classes can have the member protected because it is the only one that accepts inheritance. Obviously which classes sealed cannot benefit from protected since they will never be inherited.

The member internal is viewed by the entire compilation unit (the Assembly), is a semi-public.

There is still the protected internal which is a mixture of the two, so the member can be seen by the whole compilation unit and the classes that inherit from it.

There is still the private protected to have the member that can be accessed from an inherited class as long as it is in the same Assembly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.