Dela via


How to: Create an Array

An array is an object, so you create it with a New (Visual Basic) clause and assign it to the array variable. You can do this as part of the array declaration, or in a subsequent assignment statement.

To create an array in the array declaration statement

  • In your declaration, add a New clause after the variable name and its parentheses. The following example declares a variable to hold an array with elements of the Date Data Type (Visual Basic), creates the array, and assigns it to the variable.

    Dim validDates() As Date = New Date() {}
    

    Following the execution of this statement, the array in variable validDates has length 0.

    Note

    The New clause must specify the type name, followed by parentheses, followed by braces, {}. The parentheses do not represent a call to an array constructor. Instead, they indicate that the object type is an array type. The braces supply initialization values. The compiler requires the braces even if you are not supplying any values. Therefore, the New clause must include both the parentheses and the braces, even if they are empty.

To create an array in a separate assignment statement

  • Use a subsequent assignment statement with a New clause. The following example declares a variable to hold an array with elements of the Integer Data Type (Visual Basic), and it creates the array and assigns it to the variable in another statement.

    Dim scores() As Integer
    scores = New Integer() {}
    

    Following the execution of these statements, the array in variable scores has length 0.

    -or-

  • Use the ReDim Statement (Visual Basic) to not only create an array but initialize its length.

    ReDim scores(4)
    

    Following the execution of this statement, the array in variable scores has length 5, with all the elements holding default values.

See Also

Tasks

How to: Declare an Array Variable

How to: Create an Array with More Than One Dimension

How to: Create an Array of Arrays

How to: Create an Array with Mixed Element Types

How to: Create an Array with No Elements

How to: Initialize an Array Variable

Troubleshooting Arrays

Concepts

Overview of Arrays in Visual Basic

Other Resources

Arrays in Visual Basic