Previous | Index | Next 

[INFO] The Erase statement doesn’t work well with VB6 static arrays

A VB6 array can be of two kinds: static or dyamic. A static array is an array whose bounds are specified right in the Dim statement, whereas a dynamic array is declared in a Dim without indexes and later instantiated by means of a Redim statement:

        ' these are static arrays
        Dim arr1(10) As Integer
        Dim arr2(1 To 20) As String
        ' this is a dynamic array
        Dim arr3() As Double
        ReDim arr3(100)

The main difference between these two array types (in VB6) is that the memory for static arrays is allocated at compile time, whereas the memory for  dynamic arrays is allocated at runtime. This detail explains why you can’t use variables or expressions in the declaration of a static array under VB6:

        Dim count As Integer
        count = 100
        Dim arr4(count) As Integer    ' <<< compilation error;

VB.NET only allows dynamic arrays and there is no simple way to simulate a static array, nor it is necessary to do so because static and dynamic arrays nearly always behave in the same manner.

A minor (and underdocumented) exception to this rule is the Erase statement. If a static array is erased then the each and every element of the array is reset to its default value (zero, a null string, or Nothing), but the array’s bounds aren’t modified. Conversely, if a dynamic array is erased then the memory block allocated for the array is released and any attempt to reference one of its elements causes a runtime error.

To work around this problem and preserve functional equivalence, VB Migration Partner converts the Erase keyword in two possible ways. It generates a call to the Erase6 helper method for dynamic arrays and a call to ClearArray6 method for static arrays. Additionally to resetting all individual array elements, the ClearArray6 method ensures that UDTs (structures) inside the array are correctly initialized, if necessary.


Previous | Index | Next