VB.NET - Tip

Initializing VB.NET Arrays


In vb 6 trying to get the ubound of a array that was not yet dimensioned would result in an error. One solution around this was to write a wrapper of the ubound function, which would return -1 if the array had not been initialized. This solution is no longer necessary in VB.NET though the issue still needs to be handled, there is a much simpler solution. When you declare the array in vb.net give it a -1 as a dimension. When getuppperbound(0) is run on it, it will return a -1. This makes initial iteration and filling of arrays much easier than having to check and redim it first. Keep in mind if you try and read or write the value at -1 you will get an error.

The Code:

     Private Sub LoadArray()
         Dim theArray(-1) As int32
         Dim i As Integer

        'make array of values from 0 to 100
	For i = 0 To 100
             With theArray
                 ReDim Preserve theArray(.GetUpperBound(0) + 1)
                 theArray(.GetUpperBound(0)) = i
             End With

     End Sub

About this page: