VBfx / Common / Open Arrays


Arrays in Visual Basic are quite flexible, they can be resized (re-dimensioned) wherever you need it. However, there are 2 ways of declaring a array, see the following snippet:

'Method 1
Dim X(10) as Long

'Method 2
Dim X() as Long
ReDim X(10)

The first method defines 11 elements of X (0 to 10). If you declare a array like this you should not change it's size later! It works, but it makes code harder to understand.

The second method declares no elements of X, it just says that X is an array. However in the next line the dimension (size) of X is set to 10 (so we get 11 elements again). Whenever you have arrays that change in size you should declare them like this. In most cases I also declare a Count variable that holds the number of elements in X, this is quite usefull if you're working with the array size.

Resizing arrays

Note that this works for both declaration methods above! Examples of re-dimensioning:

ReDim Temp(5)
ReDim Temp(DataCount)
ReDim Preserve Players(20)
ReDim Preserve Shots(ShotCount)

Whenever you need more space in your array you can use ReDim to change it's size. If you want to keep the array data you'll have to use ReDim Preserve instead. If you just use ReDim the array data will be cleared!

If you don't need an array any longer and want to release all of it's elements you can use Erase to do this:

'Create array
Dim X() as Long

'Resize array
ReDim X(10)

'Do usefull things here
X(1) = 120
X(2) = X(1)

'Release memory
Erase X

Note that ReDim X(0) would still declare 1 element in X! Using Erase is the only way to remove all elements of an array!