Local Declaration Statements

 <  Day Day Up  >  

A local declaration statement declares a variable that can be used within a method. Local declarations can choose not to specify a type for the variable; if no type is specified, the type of the variable is assumed to be Object .

 Dim x As Integer Dim y              ' The type of the variable is Object Dim z As Long 


In general, it is a good idea to explicitly declare the types of variables. Besides making it easy to see with a glance what type variables are, it produces faster code because the compiler can know at compile time what type a variable is. The Option Strict statement at the beginning of a source file requires that all variable declarations have an explicit type.

Multiple variables can be declared in one of two ways. If all the variables being declared are the same type, the names can be listed separated by commas, with the type specified at the end of the declaration. Otherwise, each local variable declaration must be separated by commas. The two forms can also be combined within the same statement.

 Dim x, y As Integer Dim a As Integer, b As Long ' c, d and e are of type Double; f and g are of type Single Dim c, d, e As Double, f, g As Single Dim h, i, j ' Types are all Object 

Local variables are in scope only from the point of declaration to the end of the statement block in which they were declared. In the following example, the first reference to x is invalid because it attempts to refer to x before it is declared. The third reference to x is invalid because it attempts to refer to x outside the block in which it was declared.

 Dim y As Integer For y = 1 To 10   x = 10  ' Error: x not declared yet   Dim x As Integer   x = 20 Next y x = 30    ' Error: Can't refer to x outside of For loop 

A local variable can be named using any valid name, provided that the name is not already used anywhere in the local variable's scope. Because locals are scoped to their containing block, this means two locals can be declared with the same name, provided that their scopes don't overlap. For example:

 Dim y As Integer If y > 0 Then   Dim x As Integer   x = y * 10   Console.WriteLine(x) End If If y < 0 Then   Dim x As Long   Dim y As Long = 5  ' Error: y already declared in this scope   x = y * 20   Console.WriteLine(x) End If 

In this example, the variable x can be declared in two places because the scopes of the two variables do not overlap. The declarations of the variable y , however, will cause an error because the scope of the y in the If statement overlaps the scope of the outer y .

Type Characters

It is also possible to declare the type of a variable by using a type character at the end of a name. The type characters are % for Integer , & for Long , ! for Single , # for Double , @ for Decimal , and $ for String . For example:

 Dim x%      ' Type is Integer Dim y@      ' Type is Decimal Dim z$      ' Type is String 

Type characters can also be used when you are referring to a local variable, provided that the type character matches the type of the variable. In the following example, the reference to x is correct, while the reference to z will give an error because the types don't match.

 Dim x As Integer, z As String x% = 5 z@ = 10           ' Error: Type character doesn't match type. 


Type characters on variables are supported purely for historical reasons, and their use is discouraged.


Local variables can have initializers , which give a local variable an initial value. Initializers are specified by following the local declaration with an equals sign ( = ) and the expression to assign to the variable. Multiple variables in a declaration can be initialized , but only if they have separate As clauses.

 Dim x As Integer = 5 Dim y As String = Console.ReadLine() Dim a As Integer = 6, b As Integer = 7 

Initializers are equivalent to assignment statements (see the next main section) at the point of declaration. Every time execution reaches the local declaration statement, the variable is initialized.

 Dim i As Integer For i = 1 to 10   Dim x As Integer = 5   Console.WriteLine(x)   x = i Next i 

In this example, the value 5 is printed ten times, because every time the declaration line is reached, the local is reinitialized with the value 5. The example is equivalent to this code.

 Dim i As Integer For i = 1 to 10   Dim x As Integer   x = 5   Console.WriteLine(x)   x = i Next i 


Local constants can also be declared; they use the same syntax as local variable declarations except that they use the keyword Const instead of Dim and must supply a constant expression initializer. Local constants can be used in the same way as local variables except that their value cannot be changed.

 Dim i As Integer Const Lower As Integer = 1 Const Upper As Integer = 10 For i = Lower to Upper   Console.WriteLine(i) Next i 

Static Locals

Static locals are a special kind of local variable that retain their value across calls to the method. Normally, local variables are destroyed and lose their value when the method they are contained in exits. However, static locals are allocated in such a way that they are not destroyed when the method exits. For example, the following will print the numbers 1, 2, 3, 4, and 5 because the value of Number is preserved across calls.

 Module Test   Sub IncrementNumber()     Static Number As Integer = 0     Console.WriteLine(Number)     Number += 1   End Sub   Sub Main()     For i As Integer = 1 to 5       IncrementNumber()     Next i   End Sub End Module 

A static local with an initializer is also special in that the initializer is only executed once, the first time that execution reaches the static declaration. In the preceding example, the static local Number is only initialized with the value 0 once.


Static local initialization is done in a thread-safe way. If an exception occurs during initialization, the initialization will not be retried, and the static local will have the default value for the type.

Static locals in an instance method are stored in the containing instance, so each instance of a type will have its own set of static locals; static locals in a shared method are stored in the containing type, so all instances of the type will share the same static local. If variables shared across all instances are needed in an instance method, shared fields can be used.

The following example demonstrates the independent initialization of a static local variable in two instances of a class.

 Class TestClass   Function InstanceValue() As Integer     Static Value As Integer = 0     Value +=1     Return Value   End Function End Class Module Test   Sub Main()     Dim t1 As TestClass = New TestClass()     Dim t2 As TestClass = New TestClass()     Console.WriteLine(t1.InstanceValue())     Console.WriteLine(t2.InstanceValue())     Console.WriteLine(t1.InstanceValue())   End Sub End Module 

This example prints the values 1, 1, and 2.

Implicit Locals

Local variables can also be declared implicitly ; that is, the compiler can infer that a local was declared even if there is no explicit Dim statement. This can happen when the compiler encounters a name that has not been previously declared. Instead of giving an error, the compiler assumes that the name refers to an implicitly declared local variable with a type of Object .

 Sub Test()   For i = 1 to 10     Console.WriteLine(i)   Next i End Sub 

In this example, the variable i is not explicitly declared, so it is assumed to be a local of type Object . Implicit locals are always considered to be declared at the top of the subroutine or function, so they are always scoped to the entire method.

 Sub Test()   Dim y As Integer   If y < 0 Then     x = y * 20     Console.WriteLine(x)   End If   x = 5 End Sub 

In this case, the fact that x is first implicitly declared within an If block does not make it invalid for x to be accessed from outside the If block. If x had been explicitly declared within the If block, however, the reference would have been invalid.

The Option Explicit statement at the beginning of a source file requires that all variables be explicitly declared.


It is highly recommended that Option Explicit always be specified. It is very easy to misspell a variable name and implicitly create a local by accident !

The following example illustrates this point.

 Dim Cost As Integer Cost = CInt(Console.ReadLine()) If Cots < 0 Then   Console.WriteLine("Invalid cost") Else   Console.WriteLine("The cost is " & Cost) End If 

In this example, the local variable name Cost is misspelled as Cots in the If statement. With implicit variable declaration allowed, this will not give an error and will instead declare a variable named Cots . The resulting behavior will not be the one intended.

 <  Day Day Up  >  

The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

Similar book on Amazon

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