This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
Declares and allocates storage space for one or more variables.
[ <attributelist> ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]] [ ReadOnly ]Dim [ WithEvents ] variablelistattributelist
Optional. SeeAttribute List.
accessmodifier
Optional. Can be one of the following:
Shared
Optional. SeeShared.
Shadows
Optional. SeeShadows.
Static
Optional. SeeStatic.
ReadOnly
Optional. SeeReadOnly.
WithEvents
Optional. Specifies that these are object variables that refer to instances of a class that can raise events. SeeWithEvents.
variablelist
Required. List of variables being declared in this statement.
variable [ , variable ... ]
Eachvariable has the following syntax and parts:
variablename [ ( [ boundslist ] ) ] [ As [ New ] datatype [ With{[ .propertyname = propinitializer [ , ... ] ] } ] ] [ = initializer ]
| Part | Description |
|---|---|
variablename | Required. Name of the variable. SeeDeclared Element Names. |
boundslist | Optional. List of bounds of each dimension of an array variable. |
New | Optional. Creates a new instance of the class when theDim statement runs. |
datatype | Optional. Data type of the variable. |
With | Optional. Introduces the object initializer list. |
propertyname | Optional. The name of a property in the class you are making an instance of. |
propinitializer | Required afterpropertyname =. The expression that is evaluated and assigned to the property name. |
initializer | Optional ifNew is not specified. Expression that is evaluated and assigned to the variable when it is created. |
The Visual Basic compiler uses theDim 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 anInteger value.
Dim numberOfStudents As IntegerYou can specify any data type or the name of an enumeration, structure, class, or interface.
Dim finished As BooleanDim monitorBox As System.Windows.Forms.FormFor a reference type, you use theNew keyword to create a new instance of the class or structure that is specified by the data type. If you useNew, 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.LabelYou can declare a variable in a procedure, block, class, structure, or module. You cannot declare a variable in a source file, namespace, or interface. For more information, seeDeclaration Contexts and Default Access Levels.
A variable that is declared at module level, outside any procedure, is amember variable orfield. Member variables are in scope throughout their class, structure, or module. A variable that is declared at procedure level is alocal 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, andPrivate. For more information, seeAccess levels in Visual Basic.
TheDim keyword is optional and usually omitted if you specify any of the following modifiers:Public,Protected,Friend,Protected Friend,Private,Shared,Shadows,Static,ReadOnly, orWithEvents.
Public maximumAllowed As DoubleProtected Friend currentUserName As StringPrivate salary As DecimalStatic runningTotal As IntegerIfOption Explicit is on (the default), the compiler requires a declaration for every variable you use. For more information, seeOption Explicit Statement.
You can assign a value to a variable when it is created. For a value type, you use aninitializer 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 = 10Dim message As String = "Just started"If an initializer is specified and a data type is not specified in anAs clause,type inference is used to infer the data type from the initializer. In the following example, bothnum1 andnum2 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 = 3Type inference applies at the procedure level. It does not apply outside a procedure in a class, structure, module, or interface. For more information about type inference, seeOption Infer Statement andLocal Type Inference.
For information about what happens when a data type or initializer is not specified, seeDefault Data Types and Values later in this topic.
You can use anobject initializer to declare instances of named and anonymous types. The following code creates an instance of aStudent class and uses an object initializer to initialize properties.
Dim student1 As New Student With {.First = "Michael", .Last = "Tucker"}For more information about object initializers, seeHow to: Declare an Object by Using an Object Initializer,Object Initializers: Named and Anonymous Types, andAnonymous Types.
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 DateIf you declare more than one variable with oneAs clause, you cannot supply an initializer for that group of variables.
You can specify different data types for different variables by using a separateAs clause for each variable you declare. Each variable takes the data type specified in the firstAs clause encountered after itsvariablename 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 DoubleYou can declare a variable to hold anarray, which can hold multiple values. To specify that a variable holds an array, follow itsvariablename immediately with parentheses. For more information about arrays, seeArrays.
You can specify the lower and upper bound of each dimension of an array. To do this, include aboundslist inside the parentheses. For each dimension, theboundslist 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 21Integer elements. When you access the array, the index can vary from 0 through 20.
Dim totals(20) As IntegerDim totals(0 To 20) As IntegerThe following statement declares a two-dimensional array of typeDouble. 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 DoubleAn 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 ofNothing until you initialize at least some of its elements. TheDim 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 ByteYou can declare azero-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 valueNothing. 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, seeArrays.
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}}For more information about array literals, seeArrays.
The following table describes the results of various combinations of specifying the data type and initializer in aDim statement.
| Data type specified? | Initializer specified? | Example | Result |
|---|---|---|---|
| No | No | Dim qty | IfOption Strict is off (the default), the variable is set toNothing.If Option Strict is on, a compile-time error occurs. |
| No | Yes | Dim qty = 5 | IfOption Infer is on (the default), the variable takes the data type of the initializer. SeeLocal Type Inference. If Option Infer is off andOption Strict is off, the variable takes the data type ofObject.If Option Infer is off andOption 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 (includingByte andSByte) | 0 |
Char | Binary 0 |
All reference types (includingObject,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.
AStatic 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 isShared.
| 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 isShared | 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'tShared | The first time the procedure is called on a specific instance | When the instance is released for garbage collection (GC) |
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 theStatic modifier to declare member variables. At procedure level, you cannot useShared,Shadows,ReadOnly,WithEvents, or any access modifiers to declare local variables.
You can specify what code can access a variable by supplying anaccessmodifier. 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 specifyWithEvents only on member variables, not on local variables inside a procedure. If you specifyWithEvents, the data type of the variable must be a specific class type, notObject. You cannot declare an array withWithEvents. For more information about events, seeEvents.
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.
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 theIDisposable interface to provide a way to release resources before a garbage collection. A class that implements that interface exposes aDispose method that can be called to force valuable resources to be released immediately.
TheUsing statement automates the process of acquiring a resource, executing a set of statements, and then disposing of the resource. However, the resource must implement theIDisposable interface. For more information, seeUsing Statement.
The following example declares variables by using theDim statement with various options.
' Declare and initialize a Long variable.Dim startingAmount As Long = 500' 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 29End SubPrivate 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 IfEnd FunctionIn the following example, thespeedValue variable is declared at the class level. ThePrivate keyword is used to declare the variable. The variable can be accessed by any procedure in theCar 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: 45Public 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 SubEnd ClassWas this page helpful?
Need help with this topic?
Want to try using Ask Learn to clarify or guide you through this topic?
Was this page helpful?
Want to try using Ask Learn to clarify or guide you through this topic?