Export (0) Print
Expand All

Dim Statement

Used at module, class, structure, procedure, or block level to declare and allocate storage space for variables.

[ <attrlist> ] [{ Public | Protected | Friend | Protected Friend | 
Private | Static }] [ Shared ] [ Shadows ] [ ReadOnly ] 
Dim [ WithEvents ] name[ (boundlist) ] [ As [ New ] type ] [ = initexpr ]

Parts

attrlist
Optional. List of attributes that apply to the variables declared in this statement. Multiple attributes are separated by commas.
Public
Optional. Variables declared with the Public keyword have public access. There are no restrictions on the accessibility of public variables.

You can use Public only at module, namespace, or file level. This means you can declare public variables in a source file or inside a module, class, or structure, but not inside a procedure. If you specify Public, you can optionally omit the Dim keyword.

Protected
Optional. Variables declared with the Protected keyword have protected access. They are accessible only from within their own class or from a derived class. Protected access is not a superset of friend access.

You can use Protected only at class level. This means you can declare protected variables inside a class but not inside a procedure, and not at module, namespace, or file level. You can use Protected only to declare members of the class. If you specify Protected, you can optionally omit the Dim keyword.

Friend
Optional. Variables declared with the Friend keyword have friend access. They are accessible from within their declaration context and from anywhere else in the same program.

You can use Friend only at module, namespace, or file level. This means you can declare friend variables in a source file or inside a module, class, or structure, but not inside a procedure. If you specify Friend, you can optionally omit the Dim keyword.

Protected Friend
Optional. Variables declared with the Protected Friend keywords have the union of protected and friend access. They can be used by code anywhere in the same program, by code in their own class, and by code in any derived classes.

You can use Protected Friend only at class level. This means you can declare protected friend variables inside a class but not inside a procedure, and not at module, namespace, or file level. You can use Protected Friend only to declare members of the class. If you specify Protected Friend, you can optionally omit the Dim keyword.

Private
Optional. Variables declared with the Private keyword have private access. They are accessible only from within their declaration context, including from members of any nested types such as procedures.

You can use Private only at module level. This means you can declare private variables inside a module, class, or structure, but not at namespace or file level and not inside a procedure. If you specify Private, you can optionally omit the Dim keyword.

Static
Optional. Variables declared with the Static keyword remain in existence and retain their latest values after termination of the procedure in which they are declared.

You can use Static only at procedure level. This means you can declare static variables inside a procedure or a block within a procedure, but not at class or module level. If you specify Static, you can optionally omit the Dim keyword.

You cannot specify Static together with either Shared or Shadows in the same variable declaration.

Shared
Optional. Indicates that this variable is shared. This means it is not associated with a specific instance of a class or structure. You can access a shared variable by qualifying it either with the class or structure name, or with the variable name of a specific instance of the class or structure.

You can use Shared only at module, namespace, or file level. This means you can declare shared variables in a source file or inside a module, class, or structure, but not inside a procedure. If you specify Shared, you can optionally omit the Dim keyword.

You cannot specify both Static and Shared in the same variable declaration.

Shadows
Optional. Indicates that this variable shadows an identically named programming element, or set of overloaded elements, in a base class. You can shadow any kind of declared element with any other kind. A shadowed element is unavailable from within the derived class that shadows it, unless the shadowing element is inaccessible, for example if it is Private.

You can use Shadows only at module, namespace, or file level. This means you can declare shadowing variables in a source file or inside a module, class, or structure, but not inside a procedure. If you specify Shadows, you can optionally omit the Dim keyword.

You cannot specify both Static and Shadows in the same variable declaration.

ReadOnly
Optional. Variables declared with the ReadOnly keyword can only be read and not written. This can be useful for creating constant members of reference types, such as an object variable with preset data members.

You can use ReadOnly only at module, namespace, or file level. This means you can declare read-only variables in a source file or inside a module, class, or structure, but not inside a procedure. If you specify ReadOnly, you can optionally omit the Dim keyword.

WithEvents
Optional. Keyword that specifies that name is an object variable that refers to an instance of a class that can raise events. You can declare as many individual variables as you like using WithEvents, but you cannot declare arrays this way.

If you use the WithEvents keyword, you cannot declare name as Object. You must declare it as the specific class that can raise the events.

name
Required. Name of the variable. Must be a valid Visual Basic identifier. You can declare as many variables as you like in the same declaration statement, specifying the name part for each one and supplying the boundlist part for arrays. Multiple variables are separated by commas.

You can declare several variables to be of the same data type. You can also specify different types for different variables or groups of variables. Each variable takes the data type specified in the first As clause encountered after its name part.

boundlist
Optional. List of non-negative integers representing the upper bounds of the dimensions of an array variable. Multiple upper bounds are separated by commas. An array can have up to 60 dimensions.

Each value in boundlist specifies the upper bound of a dimension, not the length. The lower bound is always zero, so the subscript for each dimension can vary from zero through the upper-bound value.

It is possible to use -1 to declare the upper bound of an array dimension. This signifies that the array is empty but not Nothing, a distinction required by certain common language runtime functions. However, Visual Basic code cannot successfully access such an array. If you attempt to do so, an IndexOutOfRangeException error occurs during execution.

New
Optional. Keyword that enables immediate creation of an object. If you use New when declaring the object variable, a new instance of the object is created when the Dim statement is executed.
type
Optional unless Option Strict is On. Data type of the variable. Can be Boolean, Byte, Char, Date, Decimal, Double, Integer, Long, Object, Short, Single, or String; or the name of an enumeration, structure, class, or interface. You can use a separate As clause for each variable being defined, or you can define several variables to be of the same type by using a common As clause.

If you do not specify type, the variable takes the data type of initexpr. If you do specify type, the data type of initexpr must be convertible to type. If neither type nor initexpr is present, the data type defaults to Object.

initexpr
Optional. Expression that is evaluated and assigned to the variable when it is created. If you declare more than one variable with the same As clause, you cannot supply initexpr for that group of variables.

Each attribute in the attrlist part has the following syntax and parts:

attrname [({ attrargs | attrinit })]

attrlist Parts

attrname
Required. Name of the attribute. Must be a valid Visual Basic identifier.
attrargs
Optional. List of positional arguments for this attribute. Multiple arguments are separated by commas.
attrinit
Optional. List of field or property initializers for this attribute. Multiple initializers are separated by commas.

Remarks

Variables declared with Dim are available to all code within the region containing the Dim statement. If they are declared in a module, class, or structure, but outside any procedure, they can be accessed from anywhere within that module, class, or structure. To specify their accessibility in more detail, include the Public, Protected, Friend, Protected Friend, or Private keywords.

Private TryCount As Integer
Protected Salary As Decimal
Friend ValidDate As Date
Public MaximumAllowed As Double
Protected Friend CurrentUserName As String

Variables declared inside a procedure or a block are accessible only from within that procedure or block. You cannot use any of the accessibility keywords for such variables. Their declaration statements must use either Dim or Static.

Dim Counter As Integer
Static TotalSales As Double

The Dim statement can declare the data type of a variable and initialize its contents. The declaration statements in the following example declare an Integer variable, a Boolean variable, and an object variable. These are initialized, respectively, to 10, True, and a newly created instance of the Label class in the System.Windows.Forms namespace.

Dim Quantity As Integer = 10
Dim FirstTry As Boolean = True
Dim MyLabel As New System.Windows.Forms.Label

If you do not specify an initialization value for a variable, Visual Basic initializes it to the default value for its data type. The default initialization values are as follows:

  • 0 for all numeric types (including Byte).
  • Binary 0 for Char.
  • Nothing for all reference types (including Object, String, and all arrays).
  • False for Boolean.
  • 12:00 AM of January 1 of the year 1 for Date.

Each element of a structure or array is initialized as if it were a separate variable.

You can initialize the values of an array by surrounding the initialization values with braces ({}). The following example creates an array with four elements:

Dim A1() As Integer = {0, 1, 2, 3}

For multidimensional arrays, each separate dimension is surrounded with braces. The elements are specified in row-major order. The following example illustrates this:

' Initialize each array element to its row index + its column index.
Dim A2( , ) As Integer = {{0+0, 0+1, 0+2}, {1+0 ,1+1, 1+2}}
Note   You should put all your declaration statements at the beginning of the code region in which they appear, for example a module or a procedure. If a declaration statement initializes the value of a variable, it should be executed before any other statement makes reference to the variable.

A public variable can be either early bound or late bound. Protected, friend, and private variables cannot be late bound. This means you cannot access members on a late-bound object variable unless it is declared Public. If you attempt to do this, the compiler does not generate an error, but a MissingMemberException error occurs at run time.

A static 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 or not it is Shared.

  • If the procedure is declared in a module, its static variables are initialized the first time the procedure is called, and they continue to exist until your program terminates execution.
  • If the procedure is declared as Shared within a class or structure, its static variables are initialized the first time the procedure is called either on a specific instance or on the class or structure itself. They remain in existence until the program terminates.
  • If the procedure is declared within a class or structure and is not Shared, its static variables are associated with each individual instance of the class or structure. They are initialized the first time the procedure is called in that instance, and they continue to exist until that instance is released.

Example

This example uses the Dim statement to declare variables and arrays. The lower bound for array subscripts is always 0, and the upper bound is the value that appears in the Dim statement.

' Declarations do not have to initialize their variables.
' AnyValue and MyValue are initialized by default to Nothing.
Dim AnyValue, MyValue As Object
' Number is initialized by default to 0.
Dim Number As Integer
' Multiple declarations can be of the same data type or different types.
Dim FirstNumber, SecondNumber, ThirdNumber As Integer
Dim MyDate As Date, MyValue As Single, MySwitch As Boolean
' DayArray is an array of 51 Objects indexed from 0 through 50.
Dim DayArray(50) As Object
' Matrix2 is a two-dimensional array of type Integer.
Dim Matrix2(3, 4) As Integer
' Matrix3 is a three-dimensional array of type Double.
Dim Matrix3(5, 9, 5) As Double
' BirthDay is an array of 11 dates indexed from 0 through 10.
Dim BirthDay(10) As Date
' MyArray is an array of objects. The length of the array is assigned 
' when another statement assigns an array object to MyArray.
Dim MyArray() As Object

See Also

Const Statement | ReDim Statement | Variable Declaration | Object Variables | Events and Delegates | Declaring Array Variables

Show:
© 2014 Microsoft