The Visual Basic compiler uses the Dim statement to determine the variable's data type and other information, such as what code can access the variable. The following example declares a variable to hold an Integer value.

For a reference type, you use the New keyword to create a new instance of the class or structure that is specified by the data type. If you use New, you do not use an initializer expression. Instead, you supply arguments, if they are required, to the constructor of the class from which you are creating the variable.

A variable that is declared at module level, outside any procedure, is a member variable or field. Member variables are in scope throughout their class, structure, or module. A variable that is declared at procedure level is a local variable. Local variables are in scope only within their procedure or block.

The following access modifiers are used to declare variables outside a procedure: Public, Protected, Friend, Protected Friend, and Private. For more information, see Access Levels in Visual Basic.

The Dim keyword is optional and usually omitted if you specify any of the following modifiers: Public, Protected, Friend, Protected Friend, Private, Shared, Shadows, Static, ReadOnly, or WithEvents.

Specifying an Initial Value

You can assign a value to a variable when it is created. For a value type, you use an initializer to supply an expression to be assigned to the variable. The expression must evaluate to a constant that can be calculated at compile time.

If an initializer is specified and a data type is not specified in an As clause, type inference is used to infer the data type from the initializer. In the following example, both num1 and num2 are strongly typed as integers. In the second declaration, type inference infers the type from the value 3.

If you declare more than one variable with one As clause, you cannot supply an initializer for that group of variables.

You can specify different data types for different variables by using a separate As clause for each variable you declare. Each variable takes the data type specified in the first As clause encountered after its variablename part.

Dim a, b, c AsSingle, x, y AsDouble, i AsInteger' a, b, and c are all Single; x and y are both Double

Arrays

You can declare a variable to hold an array, which can hold multiple values. To specify that a variable holds an array, follow its variablename immediately with parentheses. For more information about arrays, see Arrays in Visual Basic.

You can specify the lower and upper bound of each dimension of an array. To do this, include a boundslist inside the parentheses. For each dimension, the boundslist specifies the upper bound and optionally the lower bound. The lower bound is always zero, whether you specify it or not. Each index can vary from zero through its upper bound value.

The following two statements are equivalent. Each statement declares an array of 21 Integer elements. When you access the array, the index can vary from 0 through 20.

The following statement declares a two-dimensional array of type Double. The array has 4 rows (3 + 1) of 6 columns (5 + 1) each. Note that an upper bound represents the highest possible value for the index, not the length of the dimension. The length of the dimension is the upper bound plus one.

You can leave all the bounds blank in an array declaration. If you do this, the array has the number of dimensions you specify, but it is uninitialized. It has a value of Nothing until you initialize at least some of its elements. The Dim statement must specify bounds either for all dimensions or for no dimensions.

You can declare a zero-length array by declaring one of the array's dimensions to be -1. A variable that holds a zero-length array does not have the value Nothing. Zero-length arrays are required by certain common language runtime functions. If you try to access such an array, a runtime exception occurs. For more information, see Arrays in Visual Basic.

You can initialize the values of an array by using an array literal. To do this, surround the initialization values with braces ({}).

If Option Infer is Off and Option Strict is Off, the variable takes the data type of Object.

If Option Infer is Off and Option Strict is On, a compile-time error occurs.

Yes

No

Dim qty As Integer

The variable is initialized to the default value for the data type. See the table later in this section.

Yes

Yes

Dim qty
As Integer = 5

If the data type of the initializer is not convertible to the specified data type, a compile-time error occurs.

If you specify a data type but do not specify an initializer, Visual Basic initializes the variable to the default value for its data type. The following table shows the default initialization values.

Data type

Default value

All numeric types (including Byte and SByte)

0

Char

Binary 0

All reference types (including Object, String, and all arrays)

Nothing

Boolean

False

Date

12:00 AM of January 1 of the year 1 (01/01/0001 12:00:00 AM)

Each element of a structure is initialized as if it were a separate variable. If you declare the length of an array but do not initialize its elements, each element is initialized as if it were a separate variable.

Static Local Variable Lifetime

A Static local variable has a longer lifetime than that of the procedure in which it is declared. The boundaries of the variable's lifetime depend on where the procedure is declared and whether it is Shared.

Procedure declaration

Variable initialized

Variable stops existing

In a module

The first time the procedure is called

When your program stops execution

In a class or structure, procedure is Shared

The first time the procedure is called either on a specific instance or on the class or structure itself

When your program stops execution

In a class or structure, procedure isn't Shared

The first time the procedure is called on a specific instance

When the instance is released for garbage collection (GC)

Attributes and Modifiers

You can apply attributes only to member variables, not to local variables. An attribute contributes information to the assembly's metadata, which is not meaningful for temporary storage such as local variables.

At module level, you cannot use the Static modifier to declare member variables. At procedure level, you cannot use Shared, Shadows, ReadOnly, WithEvents, or any access modifiers to declare local variables.

You can specify what code can access a variable by supplying an accessmodifier. Class and module member variables (outside any procedure) default to private access, and structure member variables default to public access. You can adjust their access levels with the access modifiers. You cannot use access modifiers on local variables (inside a procedure).

You can specify WithEvents only on member variables, not on local variables inside a procedure. If you specify WithEvents, the data type of the variable must be a specific class type, not Object. You cannot declare an array with WithEvents. For more information about events, see Events (Visual Basic).

Note

Code outside a class, structure, or module must qualify a member variable's name with the name of that class, structure, or module. Code outside a procedure or block cannot refer to any local variables within that procedure or block.

Releasing Managed Resources

The .NET Framework garbage collector disposes of managed resources without any extra coding on your part. However, you can force the disposal of a managed resource instead of waiting for the garbage collector.

If a class holds onto a particularly valuable and scarce resource (such as a database connection or file handle), you might not want to wait until the next garbage collection to clean up a class instance that's no longer in use. A class may implement the IDisposable interface to provide a way to release resources before a garbage collection. A class that implements that interface exposes a Dispose method that can be called to force valuable resources to be released immediately.

The Using statement automates the process of acquiring a resource, executing a set of statements, and then disposing of the resource. However, the resource must implement the IDisposable interface. For more information, see Using Statement (Visual Basic).

' Declare and initialize a Long variable.Dim startingAmount AsLong = 500
' Declare a variable that refers to a Button object,' create a Button object, and assign the Button object' to the variable.Dim switchButton AsNew System.Windows.Forms.Button
' Declare a local variable that always retains its value,' even after its procedure returns to the calling code.Static totalSales AsDouble' Declare a variable that refers to an array.Dim highTemperature(31) AsInteger' Declare and initialize an array variable that' holds four Boolean check values.Dim checkValues() AsBoolean = {False, False, True, False}

The following example lists the prime numbers between 1 and 30. The scope of local variables is described in code comments.

PublicSub ListPrimes()
' The sb variable can be accessed only' within the ListPrimes procedure.Dim sb AsNew System.Text.StringBuilder()
' The number variable can be accessed only' within the For...Next block. A different' variable with the same name could be declared' outside of the For...Next block.For number AsInteger = 1 To 30
If CheckIfPrime(number) = TrueThen
sb.Append(number.ToString & " ")
EndIfNext
Debug.WriteLine(sb.ToString)
' Output: 2 3 5 7 11 13 17 19 23 29EndSubPrivateFunction CheckIfPrime(ByVal number AsInteger) AsBooleanIf number < 2 ThenReturnFalseElse' The root and highCheck variables can be accessed' only within the Else block. Different variables' with the same names could be declared outside of' the Else block.Dim root AsDouble = Math.Sqrt(number)
Dim highCheck AsInteger = Convert.ToInt32(Math.Truncate(root))
' The div variable can be accessed only within' the For...Next block.For div AsInteger = 2 To highCheck
If number Mod div = 0 ThenReturnFalseEndIfNextReturnTrueEndIfEndFunction

In the following example, the speedValue variable is declared at the class level. The Private keyword is used to declare the variable. The variable can be accessed by any procedure in the Car class.