How to VB.Net Dyanamic Array

Dynamic arrays are implemented using the List(Of T) class, which provides a collection that can grow or shrink dynamically as needed. Here are some important functions and examples of working with dynamic arrays using the List(Of T) class:

Important functions in VB.Net Dyanamic Array

Add Method

The Add method is used to add an element to the end of the dynamic array.

Dim numbers As New List(Of Integer) numbers.Add(10) numbers.Add(20) numbers.Add(30)

Count Property

The Count property returns the number of elements in the dynamic array.

Dim numbers As New List(Of Integer) numbers.Add(10) numbers.Add(20) numbers.Add(30) Dim count As Integer = numbers.Count

Remove Method

The Remove method is used to remove the first occurrence of a specific element from the dynamic array.

Dim numbers As New List(Of Integer) numbers.Add(10) numbers.Add(20) numbers.Add(30) numbers.Remove(20)

Contains Method

The Contains method is used to check if a specific element exists in the dynamic array. It returns a Boolean value indicating the presence of the element.

Dim numbers As New List(Of Integer) numbers.Add(10) numbers.Add(20) numbers.Add(30) Dim hasTwenty As Boolean = numbers.Contains(20)

Insert Method

The Insert method is used to insert an element at a specified index position in the dynamic array.

Dim numbers As New List(Of Integer) numbers.Add(10) numbers.Add(20) numbers.Add(30) numbers.Insert(1, 15)

Clear Method

The Clear method is used to remove all elements from the dynamic array.

Dim numbers As New List(Of Integer) numbers.Add(10) numbers.Add(20) numbers.Add(30) numbers.Clear()

Dynamic arrays offer the flexibility to adjust the size of an array during runtime, enabling the storage of an uncertain number of elements when creating a program. These arrays are particularly useful in scenarios where the precise quantity of elements to be stored is unknown.

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.

The provided VB.NET source code showcases a selection of frequently utilized functions.

Full Source VB.NET
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