How to: Change the Size of an Array

You resize an array variable by assigning a new array object to it. You can use either a standard assignment statement or the ReDim Statement (Visual Basic). In either case, the original array is replaced with a completely new one, and the array variable points to the new array.

Resizing an array helps you manage memory efficiently. For example, you can start with a small array and then increase its size if you need more elements. Alternatively, you can start with a large array and then reduce its size when you no longer need all of it. This technique takes up the additional memory only when you need it.

To resize an array variable using a standard assignment statement

  1. Create the new array object, specifying the new dimension lengths.

  2. Assign the new array object to the array variable.

    Dim thisArrayVariable() As Integer = New Integer(99) {}
    thisArrayVariable = New Integer(49) {}
    

To resize an array variable using the ReDim statement

  • Specify the new dimension lengths for the array variable in the ReDim statement.

    Dim thisArrayVariable() As Integer = New Integer(99) {}
    ReDim thisArrayVariable(9)
    

When you ReDim an array, the existing values of its elements are normally lost. However, you can retain them by including the Preserve keyword in the ReDim statement.

To resize an array variable preserving existing element values

  1. Specify the new dimension lengths for the array variable in the ReDim statement.

  2. Add the Preserve keyword in the ReDim statement. The following example creates a new array, initializes its elements from the corresponding elements of the existing array in arrayToIncrease, and assigns the new array to the array variable arrayToIncrease.

    Dim arrayToIncrease(9, 49)
    ReDim Preserve arrayToIncrease(9, 199)
    

If you use Preserve on a multidimensional array, you can change only the last dimension length. If you attempt to change any of the other dimensions, an ArrayTypeMismatchException exception occurs.

If you resize a large array using the Preserve keyword, keep in mind that Visual Basic must copy all the existing elements into the new array. This can make your performance slower.

See Also

Tasks

How to: Declare an Array Variable

How to: Create an Array

How to: Initialize an Array Variable

How to: Determine the Size of an Array

How to: Determine the Length of One Dimension of an Array

How to: Assign One Array to Another Array

How to: Change an Array to a Different Array

Troubleshooting Arrays

Concepts

Array Size in Visual Basic

Other Resources

Arrays in Visual Basic