How to VB.Net Dyanamic Array

Dynamic Arrays can resize the capability of the Array at runtime .when you are in a situation that you do not know exactly the number of elements to store in array while you making the program. In that situations we are using Dynamic Array .

Initial declaration

Dim scores() As Integer

Resizing

ReDim scores(1)

If you want to keep the existing items in the Array , you can use the keyword Preserve .

ReDim Preserve scores(2)

In this case the Array dynamically allocate one more String value and keep the existing values.




Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
        Dim i As Integer
        Dim scores() As Integer

        ReDim scores(1)
        scores(0) = 100
        scores(1) = 200

        For i = 0 To scores.Length - 1
            MsgBox(scores(i))
        Next

        ReDim Preserve scores(2)

        scores(2) = 300

        For i = 0 To scores.Length - 1
            MsgBox(scores(i))
        Next
    End Sub
End Class

When you execute this source code , the first loop shows first two values stored in the Array. Next loop shows the whole value stored in the Array.

 VB.NET Collections - Related Contents


 VB.NET Collections - Related Programs

.