共用方式為


Dim Statement (Visual Basic) 

Declares and allocates storage space for one or more variables.

[ <attributelist> ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]] [ ReadOnly ] 
Dim [ WithEvents ] variablelist

Parts

  • Shared
    Optional. See Shared.
  • Static
    Optional. See Static.
  • WithEvents
    Optional. Specifies that these are object variables that refer to instances of a class that can raise events. See WithEvents.
  • 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 ] [ = initializer ]

    Part Description

    variablename

    Required. Name of the variable. See Declared Element Names.

    boundslist

    Optional. List of bounds of each dimension of an array variable.

    New

    Optional. Creates a new instance of the class when the Dim statement runs.

    datatype

    Required if Option Strict is On. Data type of the variable.

    initializer

    Optional if New is not specified. Expression that is evaluated and assigned to the variable when it is created.

Remarks

You should declare every variable you use in your program, to tell the Visual Basic compiler the variable's data type and other information such as what code can access it. The following example declares a variable to hold an Integer value.

Dim numberOfStudents As Integer

You can use Dim only at module or procedure level. This means the declaration context for a variable must be a class, structure, module, procedure, or block, and cannot be a source file, namespace, or interface. For more information, see Declaration Contexts and Default Access Levels.

If Option Explicit is On (the default), the compiler requires a declaration for every variable you use. If you turn Option Explicit Off, every undeclared variable defaults to the Object Data Type, which might not be your intention.

You can specify each variable's data type in the Dim statement. You can also specify an initial value. If you do not, Visual Basic uses default settings. For more information, see "Data Type Rules" and "Default Values" under "Detailed Information" on this Help page. The following example declares and initializes a String variable.

Dim summary As String = "Summary of results" 

You can specify what code can access a variable by supplying an accessmodifier in the Dim statement. For more information, see "Modifiers" and "Access Level" under "Detailed Information" on this Help page.

You can declare a variable to hold an array, which can hold multiple values. For more information, see "Array Rules" under "Detailed Information" on this Help page. For more information on arrays, see Arrays in Visual Basic. The following example declares an Integer array variable.

Dim days() As Integer 

In general, you should put all your Dim statements at the beginning of the code region in which you use the variables. For more information, see "Troubleshooting" under "Detailed Information" on this Help page.

Detailed Information

This section covers the following areas in detail:

  • Declaration

  • Data types

  • Arrays

  • Behavior

  • Troubleshooting

Declaration Rules

  • Declaration Context. A variable declared at module level, outside any procedure, is a member variable or field; it is a member of the class, structure, or module that declares it.

    A variable declared at procedure level is a local variable; it is local to the procedure or block that declares it.

  • Attributes. 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.

  • Implicit Use of Dim. If you specify any of the modifiers Public, Protected, Friend, Protected Friend, Private, Shared, Shadows, Static, ReadOnly, or WithEvents, you can optionally omit the Dim keyword.

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

    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.

  • WithEvents Variables. You can specify WithEvents only on member variables, not on local variables inside a procedure.

    If you specify WithEvents, the data type of the variables must be a specific class type and not Object. You cannot declare an array with WithEvents.

    For more information on events, see Events and Event Handlers.

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

    Dim lastTime, nextTime, allTimes() As Date
    

Data Type Rules

  • Data Types. The Dim statement can declare the data type of a variable. 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
    
  • Default Type. If you do not specify datatype, the variable takes the data type of initializer. If neither datatype nor initializer is present, the data type defaults to the Object Data Type. If you specify both datatype and initializer, the data type of initializer must be convertible to datatype.

  • Different Types. You can specify different data types for different variables by using a separate As clause for each variable you declare. Alternatively, you can declare several variables to be of the same type by using a common As clause. 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
    
  • Initialization. The Dim statement can initialize the contents of selected variables in variablelist. For a value type, you use 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"
    

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

    Dim bottomLabel As New System.Windows.Forms.Label
    

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

Array Rules

  • Array Variables. To specify that a variable in variablelist is an array, you follow its variablename immediately with parentheses. 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
    

    An array can have from 1 to 32 dimensions.

    For more information, see Arrays in Visual Basic.

  • Array Bounds. You can specify the lower and upper bound of each dimension. To do this, you 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.

    Dim matrix2(3, 5) As Double
    

    Note that an upper bound represents the highest possible value for that index, not the length of that dimension, which is the upper bound plus one.

  • Blank Array Bounds. 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, so 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 none of them.

    Dim messages() As String
    
  • Empty Arrays. 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. For more information, see How to: Create an Array with No Elements.

  • Array Initialization. You can initialize the values of an array by surrounding the initialization values with braces ({}).

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

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

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

Behavior

  • Default Values. If you do not specify initializer for a variable, Visual Basic initializes it 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.

  • Access Level. Local variables (inside a procedure) default to public access, and you cannot use any access modifiers on them.

    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.

  • Scope. Local variables are in scope only within their procedure or block. Member variables are in scope throughout their class, structure, or module.

  • Qualification. 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.

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

    Procedure declaration Variable initialized Variable ceases to exist

    In a module

    The first time the procedure is called

    When your program terminates execution

    In a class or structure, Shared

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

    When your program terminates execution

    In a class or structure, not Shared

    The first time the procedure is called on a specific instance

    When the instance is released for garbage collection (GC)

Troubleshooting

  • Execution Order. The Dim statement is not itself an executable statement. However, if it initializes one or more variables, the initializations are treated as assignment statements. This means that a variable's value undergoes the following steps:

    1. On the first entry into the code element declaring the variable, Visual Basic initializes it to the default value for its data type.

    2. When execution arrives at the variable's Dim statement, Visual Basic initializes it to the value supplied in the Dim statement.

    3. Whenever execution returns to the variable's Dim statement, Visual Basic sets it once again to the value supplied in the Dim statement.

    This has the following implications when you use a Dim statement to initialize a variable:

    • If you use the variable before executing the Dim statement, its value is the default for its data type, not the value supplied in the Dim statement.

    • If execution never reaches the Dim statement, the variable is never initialized to the value supplied in the Dim statement.

    • If you alter the value but then return to the Dim statement, your altered value is replaced by the value supplied in the Dim statement.

    If you put all your Dim statements at the beginning of the code region in which they appear, for example a module or a procedure, your code initializes them as you intend.

Example

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

' The following statement declares and initializes a Long variable.
Dim startingAmount As Long = 500
' The following statement declares a variable that refers to a Button 
' object, creates a new Button object, and assigns it to the variable.
Dim switchButton As New System.Windows.Forms.Button
' The following statement declares a variable that can only be 
' accessed by code in the same class, structure, or module.
Private homeTelephone As String = ""
' The following statement declares a local variable that always retains
' its value, even after its procedure returns to the calling code.
Static totalSales As Double
' The following statement declares a variable that refers to an array.
Dim highTemperature(31) As Integer
' The following statement declares and initializes an array variable 
' that holds 4 Boolean check values.
Dim checkValues() As Boolean = {False, False, True, False}

See Also

Tasks

How to: Declare an Array Variable
How to: Declare an Array Variable

Reference

Const Statement (Visual Basic)
ReDim Statement (Visual Basic)
Option Explicit Statement (Visual Basic)

Concepts

Variable Declaration in Visual Basic