Dynamic Arrays 


 

  • Arrays that grow and shrink at run-time are called dynamic arrays (also called redimmable arrays).

  • Arrays in VB.Net are all dynamic, even if declared with an initial size, like
        
    Dim dynamicArray (9) as Integer

  • Arrays in most programming languages are static, and cannot be resized.

  • Dynamic arrays are more flexible than fixed-sized arrays, because they can be re­sized anytime to accommodate new data.

A dynamic array's size can be changed anytime with ReDim. For example, the line 

ReDim dynamicArray (19) 

changes the number of elements allocated from 10 to 20.    

Note: Resizing dynamic arrays consumes processor time and can slow a program's execution, so ReDim as infrequently as possible. See note at end of page.

The total number of dimensions cannot be changed by ReDim (i.e., if the array is a two-dimensional array, it cannot become a three-dimensional array).   The ReDim statement cannot change the data type of an array variable or provide new initialization values for the array elements.

When ReDim is executed, all values contained in the array are lost. Numeric values are reset to zero and Strings are reset to a zero-length String. Values can be retained by using keyword Preserve with ReDim. For example, the line 

ReDim Preserve dynamicArray(19) 

resizes dynamicArray, preserving (i.e., retaining) the original values in the array. 

Memory allocated for a dynamic array can be deallocated (released) at run-time using keyword Erase. A dynamic array that has been deallocated must be redimensioned with ReDim before it can be used again.    

        Erase dynamicArray

Array resizing should be used sparingly.  When you call ReDim Preserve dynamicArray(19), VB.NET actually takes the array as it stands before that statement, creates a copy of it with the additional positions needed (or a smaller size), then destroys the original copy.  This is because VB.NET arrays are not truly dynamic. If you need a structure that can actually grow and shrink on the fly, use an ArrayList.

An ArrayList tutorial.  And another.