Partager via


How to: Create an Array with More Than One Dimension 

An array that uses more than one index is called a multidimensional array. As with a one-dimensional array, 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 a multidimensional array

  1. Place the appropriate number of commas inside the parentheses following the variable name. You should have one comma fewer than the number of dimensions.

  2. Place the same number of commas inside the parentheses in the New clause. You do not need commas inside the braces ({}) if you are not supplying any element values.

    The following example declares a variable to hold a two-dimensional array with elements of the Double Data Type (Visual Basic), creates the array, and assigns it to the variable.

    Dim weights(,) As Double = New Double(,) {}
    

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

    Note

    When you add dimensions to an array, the total storage needed by the array increases considerably, so use multidimensional arrays with care.

To work efficiently with a multidimensional array

  • Enclose it in a nested For loop.

    The following example initializes every element in matrix to a value between 0 and 99, based on its location in the array.

    Dim matrix(9, 9) As Double
    Dim maxDim0 As Integer = UBound(matrix, 1)
    Dim maxDim1 As Integer = UBound(matrix, 2)
    For i As Integer = 0 To maxDim0
        For j As Integer = 0 To maxDim1
            matrix(i, j) = (i * 10) + j
        Next j
    Next i
    

    A multidimensional array is not the same as a jagged array. For more information, see How to: Create an Array of Arrays.

See Also

Tasks

How to: Declare an Array Variable
How to: Create an Array
How to: Create an Array with Mixed Element Types
How to: Create an Array with No Elements
How to: Initialize a Multidimensional Array
Troubleshooting Arrays

Reference

For...Next Statement (Visual Basic)

Concepts

Multidimensional Arrays in Visual Basic

Other Resources

Arrays in Visual Basic