ReDim
 
Defines or resizes a variable-length array

Syntax

ReDim [ Shared ] [ Preserve ] symbolname([subscript [, ...]]) As datatype [, ...]
ReDim [ Shared ] [ Preserve ] As datatype symbolname([subscript [, ...]]) [, ...]

Parameters

Shared
Specifies shared (file-scope) access to the array throughout the module.
Preserve
When used with an existing array, the contents of the array will be preserved during the resize. Note that Preserve will not work with multi-dimensional arrays.
symbolname
A new or existing array id.
subscript: [ lowerbound TO ] upperbound
The lower and upper bound range for a dimension of the array. Lower bound defaults to zero (0) if not specified.
datatype
The type of elements contained in the array.

Description

ReDim can be used to define new variable-length arrays, or resize existing variable-length arrays. ReDim always produces variable-length arrays, so, unlike Dim, variable-length arrays can be defined with constant subscripts.

When defining a new variable-length array, its elements are default constructed. For simple data types like Integer or Double, the elements are initialized to zero (0). For user-defined types with a default constructor, that will be called.

When a variable-length array is resized without the Preserve clause, it's elements are destroyed, and new elements are default constructed. The Preserve clause does not destroy existing elements unless the new size of the variable-length array is smaller than it was previously. When resizing an array larger, the new elements are default constructed at the end of the array.

ReDim cannot be used on arrays contained in UDTs (user-defined Types), because currently only fixed-size arrays are supported in UDTs.

NOTE: Using ReDim within a member procedure with an array that contains an instance of the object class is undefined, and will [hopefully] result in horrible crashes.

Example

'' Define a variable-length array with 5 elements
''
ReDim array(1 To 5) As Integer

For index As Integer = LBound(array) To UBound(array)
    array(index) = index
Next

'' Resize a variable-length array with 10 elements
''
ReDim Preserve array(9) As Integer

Print "index", "value"
For index As Integer = LBound(array) To UBound(array)
    Print index, array(index)
Next

The previous program will produce the following output:

index         value
 0             1
 1             2
 2             3
 3             4
 4             5
 5             0
 6             0
 7             0
 8             0
 9             0
Differences from QB

See also