Creating arrays and resizing them-Collection of common programming errors

ReDim Preserve will do it, and if the array were declared at the module level, any code referencing it will not lose the reference. I do believe this is specific to vb, however, and there is also a performance penalty, in that this, too, is creating a copy of the array.

I haven’t checked, but I suspect the method user274204 describes above is probably the CLR-compliant way to do this . .

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    'Initialize your array:
    Dim Integers(20) As Integer

    'Output to the console, and you will see 20 elements of value 0
    Me.OutputArrayValues(Integers)

    'Iterate through each element and assign an integer Value:
    For i = 0 To UBound(Integers)
        Integers(i) = i
    Next

    'Output to console, and you will have values from 0 to 20:
    Me.OutputArrayValues(Integers)

    'Use Redim Preserve to expand the array to 30 elements:
    ReDim Preserve Integers(30)

    'output will show the same 0-20 values in elements 0 thru 20, and then 10 0 value elements:
    Me.OutputArrayValues(Integers)

    'Redim Preserve again to reduce the number of elements without data loss:
    ReDim Preserve Integers(15)

    'Same as above, but elements 16 thru 30 are gone:
    Me.OutputArrayValues(Integers)

    'This will re-initialize the array with only 5 elements, set to 0:
    ReDim Integers(5)
    Me.OutputArrayValues(Integers)


End Sub

Private Sub OutputArrayValues(ByVal SomeArray As Array)
    For Each i As Object In SomeArray
        Console.WriteLine(i)
    Next
End Sub

End Class