Information Technology Reference
In-Depth Information
Class Access Modifiers
A class can be seen and accessed by other classes in the system. This section covers the acces-
sibility of classes. Although I will use classes in the explanations and examples, since that is
what you are familiar with at this point in the text, the accessibility rules also apply to the other
types I will cover later.
The term
visible
is sometimes used for the term
accessible
. They can be used interchange-
ably. There are two levels of class accessibility—
public
and
internal
.
A class marked
public
can be accessed by code from any assembly in the system. To
make a class visible to other assemblies, use the
public
access modifier, as shown here.
Keyword
↓
public class MyBaseClass
{ ...
A class marked
internal
can be seen only by classes within its own assembly.
-
This is the default accessibility level, so unless you explicitly specify the modifier
public
in the class declaration, code outside the assembly cannot access the class.
You can explicitly declare a class as internal by using the
internal
access modifier.
-
Keyword
↓
internal class MyBaseClass
{ ...
Figure 7-13 illustrates the accessibility of
internal
and
public
classes from outside the
assembly. Class
MyClass
is not visible to the classes in the assembly on the left, because it is
marked
internal
. Class
OtherClass
, however, is visible to the classes on the left, because it
is marked
public
.
Figure 7-13.
Classes from other assemblies can access public classes but cannot access internal
classes.