Previous | Index | Next 

[HOWTO] Implement functions that return arrays with nonzero LBound

By default, VB Migration Partner doesn’t change the declaration of arrays, even if the array has a nonzero lower bound. You can change this behavior by means of the ArrayBounds pragma, but extra steps are necessary to handle arrays returned by functions and properties. For example, consider the following VB6 code:

        Function InitArray(first As Long, last As Long) As Long()
            ReDim result(first To last) As Long
            Dim i As Long
            For i = first To last: result(i) = i: Next
            InitArray = result
        End Function

For a smooth migration to .NET you should change both the type of the result array and of the return value of the InitArray function, so that both of them are of type VB6Array(Of Integer).

The first problem you face is that you can’t force VB Migration Partner to use the VB6Array type with the result array because, this array isn’t declared anywhere in the method body. (Strictly speaking, arrays are declared with the Dim keyword; the ReDim keyword only resizes an array.) To explicitly declare the array you must insert a Dim statement:

        Dim result() As Long
        ReDim result(first To last) As Long

(Notice that you actually need two distinct statements, because the Dim statement only works with constant bounds.) Once the array is explicitly declared you can use the ArrayBounds pragma to force using the VB6Array type:

        '## result.ArrayBounds ForceVB6Array
        Dim result() As Long
        ReDim result(first To last) As Long

It is essential that you use the ForceVB6Array value for the pragma’s argument; the VB6Array value isn’t sufficient if the Dim statement doesn’t define the array’s bounds.
Finally, you need to tell VB Migration Partner to change the return value of the method. You do this with a SetType pragma located outside the method body. The final code becomes therefore:

        '## InitArray.SetType VB6Array(Of Integer)
        Function InitArray(first As Long, last As Long) As Long()
            '## result.ArrayBounds ForceVB6Array
            Dim result() As Long
            ReDim result(first To last) As Long
            Dim i As Long
            For i = first To last: result(i) = i: Next
            InitArray = result
        End Function

If all the arrays declared inside the function must be rendered as VB6Array objects – as in previous example - you can take the following shortcut: just use an ArrayBounds pragma scoped at the method level, as in:

         Function InitArray(first As Long, last As Long) As Long()
             '## ArrayBounds ForceVB6Array
             ' ...
         End Function

or

        '## InitArray.ArrayBounds ForceVB6Array
         Function InitArray(first As Long, last As Long) As Long()
             ' ...
         End Function

 

Previous | Index | Next