Dim statement in visual basic

Declares and allocates storage space for one or more variables.

[ <attributelist> ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]] [ ReadOnly ] 
Dim [ WithEvents ] variablelist
Term Definition
attributelist Optional.
accessmodifier Optional. Can be one of the following:

See Access Levels in Visual Basic.

Shared Optional. See Shared.
Shadows Optional. See Shadows.
Static Optional. See Static.
ReadOnly Optional. See ReadOnly.
WithEvents Optional. Specifies that these are object variables that refer to instances of a class that can raise events.
variablelist Required. List of variables being declared in this statement.

variable [ , variable … ]

Each variable has the following syntax and parts:

variablename [ ( [ boundslist ] ) ] [ As [ New ] datatype [ With { [ .propertyname = propinitializer [ , … ] ] } ] ] [ = initializer ]

PartDescription
variablenameRequired. Name of the variable.
boundslistOptional. List of bounds of each dimension of an array variable.
NewOptional. Creates a new instance of the class when the Dim statement runs.
datatypeOptional. Data type of the variable.
WithOptional. Introduces the object initializer list.
propertynameOptional. The name of a property in the class you are making an instance of.
propinitializerRequired after propertyname =. The expression that is evaluated and assigned to the property name.
initializerOptional if New is not specified. Expression that is evaluated and assigned to the variable when it is created.

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.

Dim numberOfStudents As Integer

You can specify any data type or the name of an enumeration, structure, class, or interface.

Dim finished As Boolean
Dim monitorBox As System.Windows.Forms.Form

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.

Dim bottomLabel As New System.Windows.Forms.Label

You can declare a variable in a procedure, block, class, structure, or module. You cannot declare a variable in a source file, namespace, or interface.

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.

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.

Public maximumAllowed As Double
Protected Friend currentUserName As String
Private salary As Decimal
Static runningTotal As Integer

If Option Explicit is On (the default), the compiler requires a declaration for every variable you use.

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.

Dim quantity As Integer = 10
Dim message As String = "Just started"

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.

' Use explicit typing.
Dim num1 As Integer = 3

' Use local type inference.
Dim num2 = 3

Type inference applies at the procedure level. It does not apply outside a procedure in a class, structure, module, or interface. You can use an object initializer to declare instances of named and anonymous types. The following code creates an instance of a Student class and uses an object initializer to initialize properties.

Dim student1 As New Student With {.First = "Michael", 
                                  .Last = "Tucker"}

 

Declaring Multiple Variables

You can declare several variables in one declaration statement, specifying the variable name for each one, and following each array name with parentheses. Multiple variables are separated by commas.

Dim lastTime, nextTime, allTimes() As Date

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 As Single, x, y As Double, i As Integer
' 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.

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.

Dim totals(20) As Integer
Dim totals(0 To 20) As Integer

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.

Dim matrix2(3, 5) As Double

An array can have from 1 to 32 dimensions.

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.

' Declare an array with blank array bounds.
Dim messages() As String
' Initialize the array.
ReDim messages(4)

If the array has more than one dimension, you must include commas between the parentheses to indicate the number of dimensions.

Dim oneDimension(), twoDimensions(,), threeDimensions(,,) As Byte

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.

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

Dim longArray() As Long = {0, 1, 2, 3}

For multidimensional arrays, the initialization for each separate dimension is enclosed in braces in the outer dimension. The elements are specified in row-major order.

Dim twoDimensions(,) As Integer = {{0, 1, 2}, {10, 11, 12}}

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 Shared class or structure 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 that is not 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).

 

Examples


The following example declares variables by using the Dim statement with various options.

' Declare and initialize a Long variable.
Dim startingAmount As Long = 500

' Declare a variable that refers to a Button object,
' create a Button object, and assign the Button object
' to the variable.
Dim switchButton As New System.Windows.Forms.Button

' Declare a local variable that always retains its value,
' even after its procedure returns to the calling code.
Static totalSales As Double

' Declare a variable that refers to an array.
Dim highTemperature(31) As Integer

' Declare and initialize an array variable that
' holds four Boolean check values.
Dim checkValues() As Boolean = {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.

Public Sub ListPrimes()
    ' The sb variable can be accessed only
    ' within the ListPrimes procedure.
    Dim sb As New 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 As Integer = 1 To 30
        If CheckIfPrime(number) = True Then
            sb.Append(number.ToString & " ")
        End If
    Next

    Debug.WriteLine(sb.ToString)
    ' Output: 2 3 5 7 11 13 17 19 23 29
End Sub

Private Function CheckIfPrime(ByVal number As Integer) As Boolean
    If number < 2 Then
        Return False
    Else
        ' 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 As Double = Math.Sqrt(number)
        Dim highCheck As Integer = Convert.ToInt32(Math.Truncate(root))

        ' The div variable can be accessed only within
        ' the For...Next block.
        For div As Integer = 2 To highCheck
            If number Mod div = 0 Then
                Return False
            End If
        Next

        Return True
    End If
End Function

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.

' Create a new instance of a Car.
Dim theCar As New Car()
theCar.Accelerate(30)
theCar.Accelerate(20)
theCar.Accelerate(-5)

Debug.WriteLine(theCar.Speed.ToString)
' Output: 45
Public Class Car
    ' The speedValue variable can be accessed by
    ' any procedure in the Car class.
    Private speedValue As Integer = 0

    Public ReadOnly Property Speed() As Integer
        Get
            Return speedValue
        End Get
    End Property

    Public Sub Accelerate(ByVal speedIncrease As Integer)
        speedValue += speedIncrease
    End Sub
End Class

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s