All .NET types and their members have scope, which represents the level of visibility and accessibility that a type or its members can have. For example, the public scope enables members of classes or structure within a class library to be reachable by other classes or assemblies. On the other hand, the private scope can prevent members of classes or structures to be reached from outside the class or structure in which they are defined. You assign scope to your objects or members via qualifiers, which are special keywords or combination of keywords that establish how an object or its members can be reached from outside the object. Table 7.1 summarizes scope levels in Visual Basic 2010.
The following code snippet gives you an alternative view of scope:
Public
and Private
qualifiers are self-explanatory, so you probably need some more information about the other ones. To make things easier, let’s create a new class that derives from the preceding ScopeDemo
, as in the following code snippet:
If you try to reach the base class’ members, you notice that only the ones marked with Friend
, Protected Friend
, and Protected
are visible to the new class (other than Public
, of course). But this happens until you are working with one assembly, more precisely with the assembly that defines all the preceding members. What about another assembly referencing the first one? If you have created a Visual Basic solution for testing the preceding code, add a new Visual Basic project to the solution, and to the new project add a reference to the previous one. In the new project, write the following code:
Dim testScope As New Scope.InheritedScopeDemo
If you try to invoke members of the testScope
object, you can see only the FirstName
and LastName
properties because they were marked as Public
. This qualifier is the only one allowing members to be reached from external assemblies. As you may imagine, establishing the appropriate scope is fundamental. For example, you might need a field for storing some data that you do not want to share with the external world; marking a field as Private
prevents derived classes from reaching the field. So you should instead mark it as Protected
or Protected Friend
according to the access level you want to grant. Particularly when working with inheritance, scope is important.
18.191.223.208