Sometimes you may not know how large to make an array. Instead of making it large enough to hold the (anticipated) maximum number of data (which means that, on the average, part of the array may be empty), you can declare a dynamic array. The size of a dynamic array can vary during the course of the program. Or you might need an array until the user has entered a bunch of data, and the application has processed it and displayed the results. Why keep all the data in memory when it is no longer needed? With a dynamic array, you can discard the data and return the resources it occupied to the system.
To create a dynamic array, declare it as usual with the Dim statement (or Public or Private), but don’t specify its dimensions:
Dim DynArray() As Integer
Code language: VB.NET (vbnet)
Later in the program, when you know how many elements you want to store in the array, use the ReDim statement to redimension the array, this time to its actual size. In the following example, UserCount is a user-entered value:
ReDim DynArray(UserCount)
Code language: VB.NET (vbnet)
The ReDim statement can appear only in a procedure. Unlike the Dim statement, ReDim is executable— it forces the application to carry out an action at runtime. Dim statements aren’t executable, and they can appear outside procedures.
A dynamic array also can be redimensioned to multiple dimensions. Declare it with the Dim statement outside any procedure, as follows:
Dim Matrix() As Double
Code language: VB.NET (vbnet)
Then use the ReDim statement in a procedure to declare a three-dimensional array:
ReDim Matrix(9, 9, 9)
Code language: VB.NET (vbnet)
Note that the ReDim statement can’t change the type of the array — that’s why the As clause is missing from the ReDim statement. Moreover, subsequent ReDim statements can change the bounds of the array Matrix but not the number of its dimensions. For example, you can’t use the statement ReDim Matrix(99, 99) later in your code.
The Preserve Keyword
Each time you execute the ReDim statement, all the values currently stored in the array are lost. Visual Basic resets the values of the elements as if the array were just declared (it resets numeric elements to zero and String elements to empty strings.) You can, however, change the size of the array without losing its data. The ReDim statement recognizes the Preserve keyword, which forces it to resize the array without discarding the existing data. For example, you can enlarge an array by one element without losing the values of the existing elements:
ReDim Preserve DynamicArray(DynArray.GetUpperBound(0) + 1)
Code language: VB.NET (vbnet)
If the array DynamicArray held 12 elements, this statement would add one element to the array: the element DynamicArray(12). The values of the elements with indices 0 through 11 wouldn’t change.