Resizing arrays in Visual Basic

ReDim is used to resize arrays in visual basic.

Example

Module Module1

    Sub Main()

        Dim MyArray(10, 10) As Integer
        ReDim MyArray(20, 20)

        Console.ReadLine()

    End Sub

End Module

In this example, all the contents in the array will be erased when it’s resized. To preserve the contents, you can use the optional Preserve keyword when redimensioning the array. However, if you’re using a multidimensional array you’ll only be able to change the last dimension when using the Preserve keyword or a runtime error will occur.

Module Module1

    Sub Main()

        Dim MyArray(10, 10) As Integer
        ReDim Preserve MyArray(10, 20) ' Allowed, and the contents will remain.
        ReDim Preserve MyArray(20, 20) ' Not allowed. A runtime error will occur.

        Console.ReadLine()

    End Sub

End Module
Share

You may also like...