Sideway
output.to from Sideway
Draft for Information Only

Content

VB.NET Declared Element Characteristics
 Characteristics of the Elements
 See also
  Lifetime in Visual Basic
 Different Lifetimes
 Beginning of Lifetime
 End of Lifetime
 Extension of Lifetime
 Static Variables of the Same Name
 Containing Elements for Static Variables
 Example
  Description
  Code
  Comments
  Compiling the Code
  Security
 See also
  Scope in Visual Basic
 Specifying Scope and Defining Variables
 Levels of Scope
  Block Scope
  Procedure Scope
  Module Scope
  Namespace Scope
 Choice of Scope
  Advantages of Local Variables
  Minimizing Scope
 See also
  How to: Control the Scope of a Variable
 Scope at Block or Procedure Level
   To make a variable visible only within a block
   To make a variable visible only within a procedure
 Scope at Module or Namespace Level
   To make a variable visible throughout a module, class, or structure
   To make a variable visible throughout a namespace
 Example
 Robust Programming
 .NET Framework Security
 See also
  Type Promotion
 Effect of Type Promotion
 Defeat of Type Promotion
  Defeat of Type Promotion for Partial Types
 Recommendations
 See also
  Access Levels in Visual Basic
 Public
 Protected
 Friend
 Protected Friend
 Private
 Private Protected
 Access Modifiers
 See also
  How to: Control the Availability of a Variable
 Private and Public Access
   To make a variable accessible only from within its module, class, or structure
   To make a variable accessible from any code that can see it
 Protected and Friend Access
   To make a variable accessible only from within its class and any derived classes
   To make a variable accessible only from within the same assembly
 Example
 .NET Framework Security
 See also
  References to Declared Elements
 Qualifying an Element Name
   To access a declared element by qualifying its name
 Members of Other Containing Elements
 References to Projects
 Importing Containing Elements
 Naming Guidelines
 Shadowing
 See also
  Source/Reference

VB.NET Declared Element Characteristics

A characteristic of a declared element is an aspect of that element that affects how code can interact with it. Every declared element has one or more of the following characteristics associated with it:

Characteristics of the Elements

The following table shows the declared elements and the characteristics that apply to each one.

Element Data Type Lifetime Scope 1 Access Level
Variable Yes Yes Yes Yes
Constant Yes No Yes Yes
Enumeration Yes No Yes Yes
Structure No No Yes Yes
Property Yes Yes Yes Yes
Method No Yes Yes Yes
Procedure (Sub or Function) No Yes Yes Yes
Procedure parameter Yes Yes Yes No
Function return Yes Yes Yes No
Operator Yes No Yes Yes
Interface No No Yes Yes
Class No No Yes Yes
Event No No Yes Yes
Delegate No No Yes Yes

1 Scope is sometimes referred to as visibility.

See also

Lifetime in Visual Basic

The lifetime of a declared element is the period of time during which it is available for use. Variables are the only elements that have lifetime. For this purpose, the compiler treats procedure parameters and function returns as special cases of variables. The lifetime of a variable represents the period of time during which it can hold a value. Its value can change over its lifetime, but it always holds some value.

Different Lifetimes

A member variable (declared at module level, outside any procedure) typically has the same lifetime as the element in which it is declared. A nonshared variable declared in a class or structure exists as a separate copy for each instance of the class or structure in which it is declared. Each such variable has the same lifetime as its instance. However, a Shared variable has only a single lifetime, which lasts for the entire time your application is running.

A local variable (declared inside a procedure) exists only while the procedure in which it is declared is running. This applies also to that procedure's parameters and to any function return. However, if that procedure calls other procedures, the local variables retain their values while the called procedures are running.

Beginning of Lifetime

A local variable's lifetime begins when control enters the procedure in which it is declared. Every local variable is initialized to the default value for its data type as soon as the procedure begins running. When the procedure encounters a Dim statement that specifies initial values, it sets those variables to those values, even if your code had already assigned other values to them.

Each member of a structure variable is initialized as if it were a separate variable. Similarly, each element of an array variable is initialized individually.

Variables declared within a block inside a procedure (such as a For loop) are initialized on entry to the procedure. These initializations take effect whether or not your code ever executes the block.

End of Lifetime

When a procedure terminates, the values of its local variables are not preserved, and Visual Basic reclaims their memory. The next time you call the procedure, all its local variables are created afresh and reinitialized.

When an instance of a class or structure terminates, its nonshared variables lose their memory and their values. Each new instance of the class or structure creates and reinitializes its nonshared variables. However, Shared variables are preserved until your application stops running.

Extension of Lifetime

If you declare a local variable with the Static keyword, its lifetime is longer than the execution time of its procedure. The following table shows how the procedure declaration determines how long a Static variable exists.

Procedure location and sharing Static variable lifetime begins Static variable lifetime ends
In a module (shared by default) The first time the procedure is called When your application stops running
In a class, Shared (procedure is not an instance member) The first time the procedure is called either on a specific instance or on the class or structure name itself When your application stops running
In an instance of a class, not Shared (procedure is an instance member) The first time the procedure is called on the specific instance When the instance is released for garbage collection (GC)

Static Variables of the Same Name

You can declare static variables with the same name in more than one procedure. If you do this, the Visual Basic compiler considers each such variable to be a separate element. The initialization of one of these variables does not affect the values of the others. The same applies if you define a procedure with a set of overloads and declare a static variable with the same name in each overload.

Containing Elements for Static Variables

You can declare a static local variable within a class, that is, inside a procedure in that class. However, you cannot declare a static local variable within a structure, either as a structure member or as a local variable of a procedure within that structure.

Example

Description

The following example declares a variable with the Static keyword. (Note that you do not need the Dim keyword when the Dim Statement uses a modifier such as Static.)

Code

VB
Function runningTotal(ByVal num As Integer) As Integer
    Static applesSold As Integer
    applesSold = applesSold + num
    Return applesSold
End Function

Comments

In the preceding example, the variable applesSold continues to exist after the procedure runningTotal returns to the calling code. The next time runningTotal is called, applesSold retains its previously calculated value.

If applesSold had been declared without using Static, the previous accumulated values would not be preserved across calls to runningTotal. The next time runningTotal was called, applesSold would have been recreated and initialized to 0, and runningTotal would have simply returned the same value with which it was called.

Compiling the Code

You can initialize the value of a static local variable as part of its declaration. If you declare an array to be Static, you can initialize its rank (number of dimensions), the length of each dimension, and the values of the individual elements.

Security

In the preceding example, you can produce the same lifetime by declaring applesSold at module level. If you changed the scope of a variable this way, however, the procedure would no longer have exclusive access to it. Because other procedures could access applesSold and change its value, the running total could be unreliable and the code could be more difficult to maintain.

See also

Scope in Visual Basic

The scope of a declared element is the set of all code that can refer to it without qualifying its name or making it available through an Imports Statement (.NET Namespace and Type). An element can have scope at one of the following levels:

Level Description
Block scope Available only within the code block in which it is declared
Procedure scope Available to all code within the procedure in which it is declared
Module scope Available to all code within the module, class, or structure in which it is declared
Namespace scope Available to all code in the namespace in which it is declared

These levels of scope progress from the narrowest (block) to the widest (namespace), where narrowest scope means the smallest set of code that can refer to the element without qualification. For more information, see "Levels of Scope" on this page.

Specifying Scope and Defining Variables

You specify the scope of an element when you declare it. The scope can depend on the following factors:

  • The region (block, procedure, module, class, or structure) in which you declare the element

  • The namespace containing the element's declaration

  • The access level you declare for the element

Use care when you define variables with the same name but different scope, because doing so can lead to unexpected results. For more information, see References to Declared Elements.

Levels of Scope

A programming element is available throughout the region in which you declare it. All code in the same region can refer to the element without qualifying its name.

Block Scope

A block is a set of statements enclosed within initiating and terminating declaration statements, such as the following:

  • Do and Loop

  • For [Each] and Next

  • If and End If

  • Select and End Select

  • SyncLock and End SyncLock

  • Try and End Try

  • While and End While

  • With and End With

If you declare a variable within a block, you can use it only within that block. In the following example, the scope of the integer variable cube is the block between If and End If, and you can no longer refer to cube when execution passes out of the block.

VB
If n < 1291 Then
    Dim cube As Integer
    cube = n ^ 3
End If

Note

Even if the scope of a variable is limited to a block, its lifetime is still that of the entire procedure. If you enter the block more than once during the procedure, each block variable retains its previous value. To avoid unexpected results in such a case, it is wise to initialize block variables at the beginning of the block.

Procedure Scope

An element declared within a procedure is not available outside that procedure. Only the procedure that contains the declaration can use it. Variables at this level are also known as local variables. You declare them with the Dim Statement, with or without the Static keyword.

Procedure and block scope are closely related. If you declare a variable inside a procedure but outside any block within that procedure, you can think of the variable as having block scope, where the block is the entire procedure.

Note

All local elements, even if they are Static variables, are private to the procedure in which they appear. You cannot declare any element using the Public keyword within a procedure.

Module Scope

For convenience, the single term module level applies equally to modules, classes, and structures. You can declare elements at this level by placing the declaration statement outside of any procedure or block but within the module, class, or structure.

When you make a declaration at the module level, the access level you choose determines the scope. The namespace that contains the module, class, or structure also affects the scope.

Elements for which you declare Private access level are available to every procedure in that module, but not to any code in a different module. The Dim statement at module level defaults to Private if you do not use any access level keywords. However, you can make the scope and access level more obvious by using the Private keyword in the Dim statement.

In the following example, all procedures defined in the module can refer to the string variable strMsg. When the second procedure is called, it displays the contents of the string variable strMsg in a dialog box.

VB
' Put the following declaration at module level (not in any procedure).
Private strMsg As String
' Put the following Sub procedure in the same module.
Sub initializePrivateVariable()
    strMsg = "This variable cannot be used outside this module."
End Sub
' Put the following Sub procedure in the same module.
Sub usePrivateVariable()
    MsgBox(strMsg)
End Sub

Namespace Scope

If you declare an element at module level using the Friend or Public keyword, it becomes available to all procedures throughout the namespace in which the element is declared. With the following alteration to the preceding example, the string variable strMsg can be referred to by code anywhere in the namespace of its declaration.

VB
' Include this declaration at module level (not inside any procedure).
Public strMsg As String

Namespace scope includes nested namespaces. An element available from within a namespace is also available from within any namespace nested inside that namespace.

If your project does not contain any Namespace Statements, everything in the project is in the same namespace. In this case, namespace scope can be thought of as project scope. Public elements in a module, class, or structure are also available to any project that references their project.

Choice of Scope

When you declare a variable, you should keep in mind the following points when choosing its scope.

Advantages of Local Variables

Local variables are a good choice for any kind of temporary calculation, for the following reasons:

  • Name Conflict Avoidance. Local variable names are not susceptible to conflict. For example, you can create several different procedures containing a variable called intTemp. As long as each intTemp is declared as a local variable, each procedure recognizes only its own version of intTemp. Any one procedure can alter the value in its local intTemp without affecting intTemp variables in other procedures.

  • Memory Consumption. Local variables consume memory only while their procedure is running. Their memory is released when the procedure returns to the calling code. By contrast, Shared and Static variables consume memory resources until your application stops running, so use them only when necessary. Instance variables consume memory while their instance continues to exist, which makes them less efficient than local variables, but potentially more efficient than Shared or Static variables.

Minimizing Scope

In general, when declaring any variable or constant, it is good programming practice to make the scope as narrow as possible (block scope is the narrowest). This helps conserve memory and minimizes the chances of your code erroneously referring to the wrong variable. Similarly, you should declare a variable to be Static only when it is necessary to preserve its value between procedure calls.

See also

How to: Control the Scope of a Variable

Normally, a variable is in scope, or visible for reference, throughout the region in which you declare it. In some cases, the variable's access level can influence its scope.

For more information, see Scope in Visual Basic.

Scope at Block or Procedure Level

To make a variable visible only within a block

  • Place the Dim Statement for the variable between the initiating and terminating declaration statements of that block, for example between the For and Next statements of a For loop.

    You can refer to the variable only from within the block.

To make a variable visible only within a procedure

  • Place the Dim statement for the variable inside the procedure but outside any block (such as a With...End With block).

    You can refer to the variable only from within the procedure, including inside any block contained in the procedure.

Scope at Module or Namespace Level

For convenience, the single term module level applies equally to modules, classes, and structures. The access level of a module level variable determines its scope. The namespace that contains the module, class, or structure also influences the scope.

To make a variable visible throughout a module, class, or structure

  1. Place the Dim statement for the variable inside the module, class, or structure, but outside any procedure.

  2. Include the Private keyword in the Dim statement.

  3. You can refer to the variable from anywhere within the module, class, or structure, but not from outside it.

To make a variable visible throughout a namespace

  1. Place the Dim statement for the variable inside the module, class, or structure, but outside any procedure.

  2. Include the Friend or Public keyword in the Dim statement.

  3. You can refer to the variable from anywhere within the namespace containing the module, class, or structure.

Example

The following example declares a variable at module level and limits its visibility to code within the module.

Module demonstrateScope  
    Private strMsg As String  
    Sub initializePrivateVariable()  
        strMsg = "This variable cannot be used outside this module."  
    End Sub  
    Sub usePrivateVariable()  
        MsgBox(strMsg)  
    End Sub  
End Module  

In the preceding example, all the procedures defined in module demonstrateScope can refer to the String variable strMsg. When the usePrivateVariable procedure is called, it displays the contents of the string variable strMsg in a dialog box.

With the following alteration to the preceding example, the string variable strMsg can be referred to by code anywhere in the namespace of its declaration.

Public strMsg As String  

Robust Programming

The narrower the scope of a variable, the fewer opportunities you have for accidentally referring to it in place of another variable with the same name. You can also minimize problems of reference matching.

.NET Framework Security

The narrower the scope of a variable, the smaller the chances that malicious code can make improper use of it.

See also

Type Promotion

When you declare a programming element in a module, Visual Basic promotes its scope to the namespace containing the module. This is known as type promotion.

The following example shows a skeleton definition of a module and two members of that module.

VB
Namespace projNamespace
    Module projModule
        Public Enum basicEnum As Integer
            one = 1
            two = 2
        End Enum
        Public Class innerClass
            Shared Sub numberSub(ByVal firstArg As Integer)
            End Sub
        End Class
    End Module
End Namespace

Within projModule, programming elements declared at module level are promoted to projNamespace. In the preceding example, basicEnum and innerClass are promoted, but numberSub is not, because it is not declared at module level.

Effect of Type Promotion

The effect of type promotion is that a qualification string does not need to include the module name. The following example makes two calls to the procedure in the preceding example.

VB
Sub usePromotion()
    projNamespace.projModule.innerClass.numberSub(projNamespace.projModule.basicEnum.one)
    projNamespace.innerClass.numberSub(projNamespace.basicEnum.two)
End Sub

In the preceding example, the first call uses complete qualification strings. However, this is not necessary because of type promotion. The second call also accesses the module's members without including projModule in the qualification strings.

Defeat of Type Promotion

If the namespace already has a member with the same name as a module member, type promotion is defeated for that module member. The following example shows a skeleton definition of an enumeration and a module within the same namespace.

VB
Namespace thisNamespace
    Public Enum abc
        first = 1
        second
    End Enum
    Module thisModule
        Public Class abc
            Public Sub abcSub()
            End Sub
        End Class
        Public Class xyz
            Public Sub xyzSub()
            End Sub
        End Class
    End Module
End Namespace

In the preceding example, Visual Basic cannot promote class abc to thisNameSpace because there is already an enumeration with the same name at namespace level. To access abcSub, you must use the full qualification string thisNamespace.thisModule.abc.abcSub. However, class xyz is still promoted, and you can access xyzSub with the shorter qualification string thisNamespace.xyz.xyzSub.

Defeat of Type Promotion for Partial Types

If a class or structure inside a module uses the Partial keyword, type promotion is automatically defeated for that class or structure, whether or not the namespace has a member with the same name. Other elements in the module are still eligible for type promotion.

Consequences. Defeat of type promotion of a partial definition can cause unexpected results and even compiler errors. The following example shows skeleton partial definitions of a class, one of which is inside a module.

VB
Namespace sampleNamespace
    Partial Public Class sampleClass
        Public Sub sub1()
        End Sub
    End Class
    Module sampleModule
        Partial Public Class sampleClass
            Public Sub sub2()
            End Sub
        End Class
    End Module
End Namespace

In the preceding example, the developer might expect the compiler to merge the two partial definitions of sampleClass. However, the compiler does not consider promotion for the partial definition inside sampleModule. As a result, it attempts to compile two separate and distinct classes, both named sampleClass but with different qualification paths.

The compiler merges partial definitions only when their fully qualified paths are identical.

Recommendations

The following recommendations represent good programming practice.

  • Unique Names. When you have full control over the naming of programming elements, it is always a good idea to use unique names everywhere. Identical names require extra qualification and can make your code harder to read. They can also lead to subtle errors and unexpected results.

  • Full Qualification. When you are working with modules and other elements in the same namespace, the safest approach is to always use full qualification for all programming elements. If type promotion is defeated for a module member and you do not fully qualify that member, you could inadvertently access a different programming element.

See also

Access Levels in Visual Basic

The access level of a declared element is the extent of the ability to access it, that is, what code has permission to read it or write to it. This is determined not only by how you declare the element itself, but also by the access level of the element's container. Code that cannot access a containing element cannot access any of its contained elements, even those declared as Public. For example, a Public variable in a Private structure can be accessed from inside the class that contains the structure, but not from outside that class.

Public

The Public keyword in the declaration statement specifies that the element can be accessed from code anywhere in the same project, from other projects that reference the project, and from any assembly built from the project. The following code shows a sample Public declaration.

VB
Public Class classForEverybody  

You can use Public only at module, interface, or namespace level. This means you can declare a public element at the level of a source file or namespace, or inside an interface, module, class, or structure, but not in a procedure.

Protected

The Protected keyword in the declaration statement specifies that the element can be accessed only from within the same class, or from a class derived from this class. The following code shows a sample Protected declaration.

VB
Protected Class classForMyHeirs  

You can use Protected only at class level, and only when you declare a member of a class. This means you can declare a protected element in a class, but not at the level of a source file or namespace, or inside an interface, module, structure, or procedure.

Friend

The Friend keyword in the declaration statement specifies that the element can be accessed from within the same assembly, but not from outside the assembly. The following code shows a sample Friend declaration.

VB
Friend stringForThisProject As String  

You can use Friend only at module, interface, or namespace level. This means you can declare a friend element at the level of a source file or namespace, or inside an interface, module, class, or structure, but not in a procedure.

Protected Friend

The Protected Friend keyword combination in the declaration statement specifies that the element can be accessed either from derived classes or from within the same assembly, or both. The following code shows a sample Protected Friend declaration.

VB
Protected Friend stringForProjectAndHeirs As String  

You can use Protected Friend only at class level, and only when you declare a member of a class. This means you can declare a protected friend element in a class, but not at the level of a source file or namespace, or inside an interface, module, structure, or procedure.

Private

The Private keyword in the declaration statement specifies that the element can be accessed only from within the same module, class, or structure. The following code shows a sample Private declaration.

VB
Private numberForMeOnly As Integer  

You can use Private only at module level. This means you can declare a private element inside a module, class, or structure, but not at the level of a source file or namespace, inside an interface, or in a procedure.

At the module level, the Dim statement without any access level keywords is equivalent to a Private declaration. However, you might want to use the Private keyword to make your code easier to read and interpret.

Private Protected

The Private Protected keyword combination in the declaration statement specifies that the element can be accessed only from within the same class, as well as from derived classes found in the same assembly as the containing class. The Private Protected access modifier is supported starting with Visual Basic 15.5.

The following example shows a Private Protected declaration:

VB
Private Protected internalValue As Integer

You can declare a Private Protected element only inside of a class. You cannot declare it within an interface or structure, nor can you declare it at the level of a source file or namespace, inside an interface or a structure, or in a procedure.

The Private Protected access modifier is supported by Visual Basic 15.5 and later. To use it, you add the following element to your Visual Basic project (*.vbproj) file. As long as Visual Basic 15.5 or later is installed on your system, it lets you take advantage of all the language features supported by the latest version of the Visual Basic compiler:

XML
<PropertyGroup>
   <LangVersion>latest</LangVersion>
</PropertyGroup>

To use the Private Protected access modifier, you must add the following element to your Visual Basic project (*.vbproj) file:

XML
<PropertyGroup>
   <LangVersion>15.5</LangVersion>
</PropertyGroup>

For more information see setting the Visual Basic language version.

Access Modifiers

The keywords that specify access level are called access modifiers. The following table compares the access modifiers.

Access modifier Access level granted Elements you can declare with this access level Declaration context within which you can use this modifier
Public Unrestricted:

Any code that can see a public element can access it
Interfaces

Modules

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates
Source file

Namespace

Interface

Module

Class

Structure
Protected Derivational:

Code in the class that declares a protected element, or a class derived from it, can access the element
Interfaces

Classes

Structures

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates
Class
Friend Assembly:

Code in the assembly that declares a friend element can access it
Interfaces

Modules

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates
Source file

Namespace

Interface

Module

Class

Structure
Protected Friend Union of Protected and Friend:

Code in the same class or the same assembly as a protected friend element, or within any class derived from the element's class, can access it
Interfaces

Classes

Structures

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates
Class
Private Declaration context:

Code in the type that declares a private element, including code within contained types, can access the element
Interfaces

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates
Module

Class

Structure
Private Protected Code in the class that declares a private protected element, or code in a derived class found in the same assembly as the bas class. Interfaces

Classes

Structures

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates
Class

See also

How to: Control the Availability of a Variable

You control the availability of a variable by specifying its access level. The access level determines what code has permission to read or write to the variable.

  • Member variables (defined at module level and outside any procedure) default to public access, which means any code that can see them can access them. You can change this by specifying an access modifier.

  • Local variables (defined inside a procedure) nominally have public access, although only code within their procedure can access them. You cannot change the access level of a local variable, but you can change the access level of the procedure that contains it.

For more information, see Access levels in Visual Basic.

Private and Public Access

To make a variable accessible only from within its module, class, or structure

  1. Place the Dim Statement for the variable inside the module, class, or structure, but outside any procedure.

  2. Include the Private keyword in the Dim statement.

    You can read or write to the variable from anywhere within the module, class, or structure, but not from outside it.

To make a variable accessible from any code that can see it

  1. For a member variable, place the Dim statement for the variable inside a module, class, or structure, but outside any procedure.

  2. Include the Public keyword in the Dim statement.

    You can read or write to the variable from any code that interoperates with your assembly.

-or-

  1. For a local variable, place the Dim statement for the variable inside a procedure.

  2. Do not include the Public keyword in the Dim statement.

    You can read or write to the variable from anywhere within the procedure, but not from outside it.

Protected and Friend Access

You can limit the access level of a variable to its class and any derived classes, or to its assembly. You can also specify the union of these limitations, which allows access from code in any derived class or in any other place in the same assembly. You specify this union by combining the Protected and Friend keywords in the same declaration.

To make a variable accessible only from within its class and any derived classes

  1. Place the Dim statement for the variable inside a class, but outside any procedure.

  2. Include the Protected keyword in the Dim statement.

    You can read or write to the variable from anywhere within the class, as well as from within any class derived from it, but not from outside any class in the derivation chain.

To make a variable accessible only from within the same assembly

  1. Place the Dim statement for the variable inside a module, class, or structure, but outside any procedure.

  2. Include the Friend keyword in the Dim statement.

    You can read or write to the variable from anywhere within the module, class, or structure, as well as from any code in the same assembly, but not from outside the assembly.

Example

The following example shows declarations of variables with Public, Protected, Friend, Protected Friend, and Private access levels. Note that when the Dim statement specifies an access level, you do not need to include the Dim keyword.

Public Class classForEverybody  
Protected Class classForMyHeirs  
Friend stringForThisProject As String  
Protected Friend stringForProjectAndHeirs As String  
Private numberForMeOnly As Integer  

.NET Framework Security

The more restrictive the access level of a variable, the smaller the chances that malicious code can make improper use of it.

See also

References to Declared Elements

When your code refers to a declared element, the Visual Basic compiler matches the name in your reference to the appropriate declaration of that name. If more than one element is declared with the same name, you can control which of those elements is to be referenced by qualifying its name.

The compiler attempts to match a name reference to a name declaration with the narrowest scope. This means it starts with the code making the reference and works outward through successive levels of containing elements.

The following example shows references to two variables with the same name. The example declares two variables, each named totalCount, at different levels of scope in module container. When the procedure showCount displays totalCount without qualification, the Visual Basic compiler resolves the reference to the declaration with the narrowest scope, namely the local declaration inside showCount. When it qualifies totalCount with the containing module container, the compiler resolves the reference to the declaration with the broader scope.

VB
' Assume these two modules are both in the same assembly.  
Module container  
    Public totalCount As Integer = 1  
    Public Sub showCount()  
        Dim totalCount As Integer = 6000  
        ' The following statement displays the local totalCount (6000).  
        MsgBox("Unqualified totalCount is " & CStr(totalCount))  
        ' The following statement displays the module's totalCount (1).  
        MsgBox("container.totalCount is " & CStr(container.totalCount))  
    End Sub  
End Module  
Module callingModule  
    Public Sub displayCount()  
        container.showCount()  
        ' The following statement displays the containing module's totalCount (1).  
        MsgBox("container.totalCount is " & CStr(container.totalCount))  
    End Sub  
End Module  

Qualifying an Element Name

If you want to override this search process and specify a name declared in a broader scope, you must qualify the name with the containing element of the broader scope. In some cases, you might also have to qualify the containing element.

Qualifying a name means preceding it in your source statement with information that identifies where the target element is defined. This information is called a qualification string. It can include one or more namespaces and a module, class, or structure.

The qualification string should unambiguously specify the module, class, or structure containing the target element. The container might in turn be located in another containing element, usually a namespace. You might need to include several containing elements in the qualification string.

To access a declared element by qualifying its name

  1. Determine the location in which the element has been defined. This might include a namespace, or even a hierarchy of namespaces. Within the lowest-level namespace, the element must be contained in a module, class, or structure.

    VB
    ' Assume the following hierarchy exists outside your code.  
    Namespace outerSpace  
        Namespace innerSpace  
            Module holdsTotals  
                Public Structure totals  
                    Public thisTotal As Integer  
                    Public Shared grandTotal As Long  
                End Structure  
            End Module  
        End Namespace  
    End Namespace  
    
  2. Determine a qualification path based on the target element's location. Start with the highest-level namespace, proceed to the lowest-level namespace, and end with the module, class, or structure containing the target element. Each element in the path must contain the element that follows it.

    outerSpace → innerSpace → holdsTotals → totals

  3. Prepare the qualification string for the target element. Place a period (.) after every element in the path. Your application must have access to every element in your qualification string.

    VB
    outerSpace.innerSpace.holdsTotals.totals.  
    
  4. Write the expression or assignment statement referring to the target element in the normal way.

    VB
    grandTotal = 9000  
    
  5. Precede the target element name with the qualification string. The name should immediately follow the period (.) that follows the module, class, or structure that contains the element.

    VB
    ' Assume the following module is part of your code.  
    Module accessGrandTotal  
        Public Sub setGrandTotal()  
            outerSpace.innerSpace.holdsTotals.totals.grandTotal = 9000  
        End Sub  
    End Module  
    
  6. The compiler uses the qualification string to find a clear, unambiguous declaration to which it can match the target element reference.

You might also have to qualify a name reference if your application has access to more than one programming element that has the same name. For example, the System.Windows.Forms and System.Web.UI.WebControls namespaces both contain a Label class (System.Windows.Forms.Label and System.Web.UI.WebControls.Label). If your application uses both, or if it defines its own Label class, you must distinguish the different Label objects. Include the namespace or import alias in the variable declaration. The following example uses the import alias.

VB
' The following statement must precede all your declarations.  
Imports win = System.Windows.Forms, web = System.Web.UI.WebControls  
' The following statement references the Windows.Forms.Label class.  
Dim winLabel As New win.Label()  

Members of Other Containing Elements

When you use a nonshared member of another class or structure, you must first qualify the member name with a variable or expression that points to an instance of the class or structure. In the following example, demoClass is an instance of a class named class1.

VB
Dim demoClass As class1 = New class1()  
demoClass.someSub[(argumentlist)]  

You cannot use the class name itself to qualify a member that is not Shared. You must first create an instance in an object variable (in this case demoClass) and then reference it by the variable name.

If a class or structure has a Shared member, you can qualify that member either with the class or structure name or with a variable or expression that points to an instance.

A module does not have any separate instances, and all its members are Shared by default. Therefore, you qualify a module member with the module name.

The following example shows qualified references to module member procedures. The example declares two Sub procedures, both named perform, in different modules in a project. Each one can be specified without qualification within its own module but must be qualified if referenced from anywhere else. Because the final reference in module3 does not qualify perform, the compiler cannot resolve that reference.

VB
' Assume these three modules are all in the same assembly.  
Module module1  
    Public Sub perform()  
        MsgBox("module1.perform() now returning")  
    End Sub  
End Module  
Module module2  
    Public Sub perform()  
        MsgBox("module2.perform() now returning")  
    End Sub  
    Public Sub doSomething()  
        ' The following statement calls perform in module2, the active module.  
        perform()  
        ' The following statement calls perform in module1.  
        module1.perform()  
    End Sub  
End Module  
Module module3  
    Public Sub callPerform()  
        ' The following statement calls perform in module1.  
        module1.perform()  
        ' The following statement makes an unresolvable name reference  
        ' and therefore generates a COMPILER ERROR.  
        perform() ' INVALID statement  
    End Sub  
End Module  

References to Projects

To use Public elements defined in another project, you must first set a reference to that project's assembly or type library. To set a reference, click Add Reference on the Project menu, or use the /reference (Visual Basic) command-line compiler option.

For example, you can use the XML object model of the .NET Framework. If you set a reference to the System.Xml namespace, you can declare and use any of its classes, such as XmlDocument. The following example uses XmlDocument.

VB
' Assume this project has a reference to System.Xml  
' The following statement creates xDoc as an XML document object.  
Dim xDoc As System.Xml.XmlDocument  

Importing Containing Elements

You can use the Imports Statement (.NET Namespace and Type) to import the namespaces that contain the modules or classes that you want to use. This enables you to refer to the elements defined in an imported namespace without fully qualifying their names. The following example rewrites the previous example to import the System.Xml namespace.

VB
' Assume this project has a reference to System.Xml  
' The following statement must precede all your declarations.  
Imports System.Xml  
' The following statement creates xDoc as an XML document object.  
Dim xDoc As XmlDocument  

In addition, the Imports statement can define an import alias for each imported namespace. This can make the source code shorter and easier to read. The following example rewrites the previous example to use xD as an alias for the System.Xml namespace.

VB
' Assume this project has a reference to System.Xml  
' The following statement must precede all your declarations.  
Imports xD = System.Xml  
' The following statement creates xDoc as an XML document object.  
Dim xDoc As xD.XmlDocument  

The Imports statement does not make elements from other projects available to your application. That is, it does not take the place of setting a reference. Importing a namespace just removes the requirement to qualify the names defined in that namespace.

You can also use the Imports statement to import modules, classes, structures, and enumerations. You can then use the members of such imported elements without qualification. However, you must always qualify nonshared members of classes and structures with a variable or expression that evaluates to an instance of the class or structure.

Naming Guidelines

When you define two or more programming elements that have the same name, a name ambiguity can result when the compiler attempts to resolve a reference to that name. If more than one definition is in scope, or if no definition is in scope, the reference is irresolvable. For an example, see "Qualified Reference Example" on this Help page.

You can avoid name ambiguity by giving all your elements unique names. Then you can make reference to any element without having to qualify its name with a namespace, module, or class. You also reduce the chances of accidentally referring to the wrong element.

Shadowing

When two programming elements share the same name, one of them can hide, or shadow, the other one. A shadowed element is not available for reference; instead, when your code uses the shadowed element name, the Visual Basic compiler resolves it to the shadowing element. For a more detailed explanation with examples, see Shadowing in Visual Basic.

See also

Source/Reference


©sideway

ID: 200900027 Last Updated: 9/27/2020 Revision: 0 Ref:

close

References

  1. Active Server Pages,  , http://msdn.microsoft.com/en-us/library/aa286483.aspx
  2. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929%28v=vs.90%29.aspx
  3. ASP Best Practices,  , http://technet.microsoft.com/en-us/library/cc939157.aspx
  4. ASP Built-in Objects,  , http://msdn.microsoft.com/en-us/library/ie/ms524716(v=vs.90).aspx
  5. Response Object,  , http://msdn.microsoft.com/en-us/library/ms525405(v=vs.90).aspx
  6. Request Object,  , http://msdn.microsoft.com/en-us/library/ms524948(v=vs.90).aspx
  7. Server Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525541(v=vs.90).aspx
  8. Application Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525360(v=vs.90).aspx
  9. Session Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms524319(8v=vs.90).aspx
  10. ASPError Object,  , http://msdn.microsoft.com/en-us/library/ms524942(v=vs.90).aspx
  11. ObjectContext Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525667(v=vs.90).aspx
  12. Debugging Global.asa Files,  , http://msdn.microsoft.com/en-us/library/aa291249(v=vs.71).aspx
  13. How to: Debug Global.asa files,  , http://msdn.microsoft.com/en-us/library/ms241868(v=vs.80).aspx
  14. Calling COM Components from ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524620(v=VS.90).aspx
  15. IIS ASP Scripting Reference,  , http://msdn.microsoft.com/en-us/library/ms524664(v=vs.90).aspx
  16. ASP Keywords,  , http://msdn.microsoft.com/en-us/library/ms524672(v=vs.90).aspx
  17. Creating Simple ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524741(v=vs.90).aspx
  18. Including Files in ASP Applications,  , http://msdn.microsoft.com/en-us/library/ms524876(v=vs.90).aspx
  19. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929(v=vs.90).aspx
  20. FileSystemObject Object,  , http://msdn.microsoft.com/en-us/library/z9ty6h50(v=vs.84).aspx
  21. http://msdn.microsoft.com/en-us/library/windows/desktop/ms675944(v=vs.85).aspx,  , ADO Object Model
  22. ADO Fundamentals,  , http://msdn.microsoft.com/en-us/library/windows/desktop/ms680928(v=vs.85).aspx
close

Latest Updated LinksValid XHTML 1.0 Transitional Valid CSS!Nu Html Checker Firefox53 Chromena IExplorerna
IMAGE

Home 5

Business

Management

HBR 3

Information

Recreation

Hobbies 8

Culture

Chinese 1097

English 339

Reference 79

Computer

Hardware 249

Software

Application 213

Digitization 32

Latex 52

Manim 205

KB 1

Numeric 19

Programming

Web 289

Unicode 504

HTML 66

CSS 65

SVG 46

ASP.NET 270

OS 429

DeskTop 7

Python 72

Knowledge

Mathematics

Formulas 8

Algebra 84

Number Theory 206

Trigonometry 31

Geometry 34

Coordinate Geometry 2

Calculus 67

Complex Analysis 21

Engineering

Tables 8

Mechanical

Mechanics 1

Rigid Bodies

Statics 92

Dynamics 37

Fluid 5

Fluid Kinematics 5

Control

Process Control 1

Acoustics 19

FiniteElement 2

Natural Sciences

Matter 1

Electric 27

Biology 1

Geography 1


Copyright © 2000-2024 Sideway . All rights reserved Disclaimers last modified on 06 September 2019