Access Modifiers

At the physical level, a C# program consists of one or more compilation units, each contained in a separate source file. When a C# program is compiled, all of the compilation units are processed together. Thus, compilation units can depend on each other, possibly in a circular fashion. An assembly is a physical container for types and the resources associated with them.

At the logical level, C# programs are organized using namespaces. Namespaces are used as a way of presenting program elements that are exposed to other programs in the same or different assemblies. Access modifiers are a way of specifying which members of a namespace will be exposed and to what degree.

In C#, an access modifier alters the default accessibility of a type or its members. The available modifiers and the defaults that are applied are shown below-

Modifier Effect Default For
private Accessible within the method or
type in which it is declared
Members of classes and structs; nested types
internal Accessible within the assembly Non-nested types
protected Accessible within a class and its derived classes -
protected internal Accessible within a class, its derived classes, or an assembly -
public Accessible everywhere Members of enums and interfaces

In this table, types include classes, structs, interfaces, enums, and delegates. The interpretation of this table for classes is as follows:
â?¢ A non-nested class is by default visible to other classes in the same assembly.
â?¢ A nested class is by default private and can have no more accessibility than its enclosing class.
â?¢ A member of a class (e.g., field, method, property) is by default private.
â?¢ An inherited class can have special access to a member in its superclass that has been tagged with the protected modifier.
Unless you are going to do cross-assembly development, the public modifier is not strictly necessary.
Interface members are always public, and no modifiers are allowed.
Namespaces cannot have private or protected members. Modifiers can only be added to types and members to make them as accessible as their enclosing methods or classes.

reference. C# Language Specification Version 3.0, September 2007, Section 10.3.5

Leave a Reply