Section 4.2. Variables


4.2. Variables

A variable can be defined as an entity that has the following six properties:


Name

A variable's name is used to identify it in code. In VB, a variable name starts with a Unicode alphabetic character or an underscore and is then followed by additional underscore characters or various Unicode characters, such as alphabetic, numeric, formatting, or combined characters. With the introduction of .NET, Microsoft recommends a new set of naming standards for use with variables and other named objects. These naming standards are discussed briefly in the "Naming Conventions" section of Chapter 1.


Address

Every variable has an associated memory address, the location where the variable's value is stored. Variables are not guaranteed to maintain a permanent memory address in .NET, so the address of a variable should not be recorded or used.


Data Type

The data type of a variable determines the possible values that the variable can assume.


Value

The value of a variable is the data content it contains at its memory address. This is also sometimes referred to as the r-value of the variable, since it is what appears on the right side of a variable assignment statement. For instance, in the code:

     Dim targetValue As Integer = 5 

the statement can be read as "store the value of 5 in memory at the address of targetValue." Because it appears on the left side of an assignment operator, the variable (or its memory location) is sometimes called an l-value.


Scope

The scope of a variable determines where in a program that variable is visible to the code. Variable scope is discussed in more detail later in this chapter.


Lifetime

A variable's lifetime determines when and for how long a particular variable exists. It may or may not be visible (that is, be in scope) for that entire period. Variable lifetime is described in more detail later in this chapter.

4.2.1. Variable Declaration

A variable declaration is an association of a variable name with a data type. For non-object variables (value types), declaration is firmly tied to variable instance creation. A declaration such as:

     Dim createMeNow As Integer 

creates an Integer variable named createMeNow. This is equivalent to:

     Dim createMeNow As Integer = New Integer 

or even:

     Dim createMeNow As New Integer 

which emphasizes the creation of a new instance of the variable object.

Multiple variables can be declared within a single statement. Although each variable generally has its own type declaration, this is not a requirement. If a variable lacks an explicit type declaration, then its type is that of the next variable with an explicit type declaration. Thus, in the line:

     Dim first As Long, second, third As Integer, fourth As String 

the variables second and third have type Integer. (In VB 6, second would have been Variant.)

Visual Basic permits the initialization of variables in the same line as their declaration. (The assigned value is called an initializer.) The statement:

     Dim alwaysInitialized As Integer = 5 

declares and creates an Integer, and assigns it an initial value of 5. Multiple assignments in a single statement also work.

     Dim first As Integer = 6, second As Integer = 9 

When using initializers, each variable must include an explicit data type.

Object variables (reference types) are declared just like their core data type counterparts:

     Dim newHire As Employee 

However, this declaration does not create an object variable; the variable's value is equal to Nothing. Object creation requires an explicit call to the object's constructor, as in:

     Dim newHire As New Employee 

or:

     Dim newHire As Employee = New Employee 

or even:

     Dim newHire As Employee     newHire = New Employee 

4.2.2. Variable Scope, Lifetime, and Access Level

Variables have a scope, which indicates where in the program the variable is recognized or visible to the code.

4.2.2.1. Local variables: block-level scope and procedure-level

All variables declared within a function, sub procedure, or property are local variables. These variables may be used only within that routine; when the routine is complete, they cease to exist (if they haven't been passed to another variable with a larger scope).

Local variables generally have procedure-level scope; they are accessible by every line of code in the procedure. These local variables often appear immediately upon entering the code of the procedure.

     Public Sub DoTheWork(  )        Dim localInt As Integer        Dim localEmp As New Employee 

Code blocks are sets of statements contained within an If statement, a For loop, a With statement, or any other similar block of code that has separate starting and ending statements. All statements that appear between the opening statement (If, ElseIf, For, With, and so on) and the closing statement (End If, Next, End With, and so on) are part of that code block. Any variable defined within a code block has block-level scope; it is only visible within that block of code. Since code blocks can be nested, block-level variables can appear at any depth within the nesting.

     Public Sub DoTheWork(ByVal fromWhen As Date, ByVal howMuch As Decimal)        If (fromWhen < Today) Then           ' ----- This variable is available within the outer-most           '       If block, which also includes the inner-most block.           '       It is not available outside the outer-most If block.           Dim simpleCalculation As Integer           If (howMuch > 0@) Then              ' ----- This variable is only available within the              '       inner-most If block.              Dim complexCalculation As Integer           End If        End If     End Sub 

Block-level variables cannot be accessed at all outside of their defined block. Consider the following code:

     If (origValue <> 0) Then        Dim inverseValue As Decimal        inverseValue = 1 / origValue     End If     ' ----- The next statement will not compile.     MsgBox(CStr(inverseValue)) 

In this code, the variable inverseValue is not recognized outside of the block in which it is defined, so the final line produces a compile-time error.

All local variables, whether procedure-level or block-level in scope, have a lifetime of the entire procedure. This means that block-level variables retain their value during the entire procedure's lifetime, even when code outside the block is being executed. In the code:

     Dim counter As Integer     For counter = 1 To 5        If (ProcessData(counter) = True) Then           Dim soFar1 As Integer           Dim soFar2 As Integer = 0           soFar1 += 1           soFar2 += 1           MsgBox("Status so far: " & soFar1 & ", " & soFar2)        End If     Next counter 

the variable soFar1 retains its value from the previous time through the If block. It displays "1" in its first MsgBox use, "2" the second time, and so on. Because the soFar2 variable includes an initializer, it is reset to that value (0, in this case) each time through the block. It always displays "1" in the MsgBox statement.

A procedure can have variables passed to it through its argument list. These variables are always procedure-level in scope.

Local variables can extend their lifetime beyond the execution timeline of the procedure in which they reside. Static variables, though local in scope, live for the entire lifetime of the class or module in which they are contained. They are declared with the Static keyword instead of the Dim keyword:

     Static longLasting As Integer = 0 

The initializer of a static variable is applied when the class or module is instantiated, not each time the statement is encountered. When you enter a procedure with a static variable, the variable will contain the same value it had the last time the procedure was used. Static variables are not allowed in the procedures of a Structure.

4.2.2.2. Module-level scope and access levels

All variables declared within a class (or structure or module), but outside of any procedure within that class, have type-level scope; they are available to all procedures within the class. However, the scope of these variables can go beyond the type level through the use of an access modifier.

Each type-level variable is defined using an access modifier keyword. (You can use Dim as well, but as Dim's access level varies between the different module types, this makes the code unclear.) The access modifier grants access in a specific order, with Public granting the most generous level of access (see Table 4-1).

Table 4-1. Access modifiers

Access modifier

Description

Public

Public variables are accessible to any code that accesses an instance of the class or structure, or that has access to the type containing the variable. If a class has a public variable, and an instance of that class is accessed from a separate project, application, or component, the public variable is fully accessible to that code.

Protected

Protected variables are accessible within the confines of a class and can be used in any code derived from that class, but cannot be accessed outside of the class. Protected variables only apply to classes; they are not available to structures or modules.

Friend

Friend variables are accessible anywhere within the assembly, but no further. Instances of a class with a friend variable consumed outside of the assembly hide the variable from that external code. Friend variables can be used in classes, structures, and modules.

Protected Friend

Using Protected and Friend together grants that variable all the benefits of both; such variables are accessible within the class and all derived classes, and within the assembly, but not outside of it. Protected Friend variables can only be used in classes, not in structures or modules.

Private

Private variables are accessible anywhere within a class, structure, or module, but not outside. They are also hidden from the custom members of derived classes.


Type-level variables have a lifetime that spans the entire lifetime of the class instance, structure instance, or module that contains it. Variables can be marked as Shared; they exist without a specific instance of the class, structure, or module being created. These variables have a lifetime that lasts for the entire application's lifetime. All members of a Module are shared by default.




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net