|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
Access Modifiers (C# Programming Guide)
Classes and structs can be restricted so that only the program or namespace they are declared in may use them. Class members can be restricted so that only derived classes can use them, or restricted so that only classes within the current namespace or program can use them. Access modifiers are keywords added to the class, struct, or member declaration to specify these restrictions. Those keywords are public, private, protected, and internal. For example:
Classes and structs that are not nested within other classes or structs can be either public or internal. A type declared as public is accessible by any other type. A type declared as internal is only accessible by types within the same assembly. Classes and structs are declared as internal by default unless the keyword public is added to the class definition, as in the previous example. Class or struct definitions can add the internal keyword to make their access level explicit. Access modifiers do not affect the class or struct itself — it always has access to itself and all of its own members.
Class or struct members can be declared with one of five types of access. They can be public or internal, like the classes and structs themselves. A class member can be declared as protected using the protected keyword, meaning that only derived types using the class as a base can access the member. By combining the protected and internal keywords, a class member can be marked protected internal — only derived types or types within the same assembly can access that member. Finally, a class or struct member can be declared as private with the private keyword, indicating that only the class or struct declaring the member is allowed access to that member.
To set the access level for a class or struct member, add the appropriate keyword to the member declaration. Some examples:
Interfaces, like classes, can be declared as public or internal types. Unlike classes, interfaces default to internal access. Interface members are always public, and no access modifiers can be applied.
Namespaces and enumeration members are always public, and no access modifiers can be applied.
Delegates have internal access by default.
Any types declared within a namespace or at the top level of a compilation unit (for example, not within a namespace, class, or struct) are internal by default, but can be made public.