Книга: C# 2008 Programmer

Access Modifiers

Access Modifiers

Chapter 4 discussed two primary access modifiers — public and private, and introduced two others: protected and internal. Let's take a look at how the latter are used. Consider the following class definition:

public class A {
 private int v;
 public int w;
 protected int x;
 internal int y;
 protected internal int z;
}

The A class has four data members, each with a different access modifiers. The fifth data member, z, has a combination of two access modifiers — protected and internal. To see the difference between all these different modifiers, create an instance of A and observe the members displayed by IntelliSense.

Figure 6-5 shows that only the variables w, y, and z are accessible.


Figure 6-5

At this moment, you can conclude that:

? The private keyword indicates that the member is not visible outside the type (class).

? The public keyword indicates that the member is visible outside the type (class).

? The protected keyword indicates that the member is not visible outside the type (class).

? The internal keyword indicates that the member is visible outside the type (class).

? The protected internal keyword combination indicates that the member is visible outside the type (class).

Now define a second class, B, that inherits from class A:

public class B : A {
 public void Method() {}
}

Try to access the class A variables from within Method(). In Figure 6-6, IntelliSense shows the variables that are accessible.


Figure 6-6

As you can see, member x is now visible (in addition to w, y, and z), so you can conclude that:

? The private keyword indicates that the member is not visible outside the type (class) or to any derived classes.

? The public keyword indicates that the member is visible outside the type (class) and to all derived classes.

? The protected keyword indicates that the member is not visible outside the type (class) but is visible to any derived classes.

? The internal keyword indicates that the member is visible outside the type (class) as well as to all derived classes.

? The protected internal keyword combination indicates that the item is visible outside the type (class) as well as to all derived classes.

From these conclusions, the difference among private, public, and protected is obvious. However, there is no conclusive difference between internal and protected internal. The internal access modifier indicates that the member is only visible within its containing assembly. The protected internal keyword combination indicates that the member is visible to any code within its containing assembly as well as derived types.

Besides applying the access modifiers to data members, you can also use them on type definitions. However, you can only use the private and public access modifiers on class definitions. 

Оглавление книги


Генерация: 0.552. Запросов К БД/Cache: 0 / 0
поделиться
Вверх Вниз