VB.NET Dynamic Array

A Dynamic array is used when we do not know how many items or elements to be inserted in an array. To resolve this problem, we use the dynamic array. It allows us to insert or store the number of elements at runtime in sequentially manner. A Dynamic Array can be resized according to the program's requirements at run time using the "ReDim" statement.

Initial Declaration of Array

Syntax:

Runtime Declaration of the VB.NET Dynamic array (Resizing)

Syntax:

The ReDim statement is used to declare a dynamic array. To resize an array, we have used a Preserve keyword that preserve the existing item in the array. The array_name represents the name of the array to be re-dimensioned. A subscript represents the new dimension of the array.

Initialization of Dynamic Array

To initialize a Dynamic Array, we have used create a string array named myArr() that uses the Dim statement in which we do not know the array's actual size. The ReDim statement is used to resize the existing array by defining the subscript (3). If we want to store one more element in index 4 while preserving three elements in an array, use the following statements.

the above array has four elements.

Also, if we want to store multiple data types in an array, we have to use a Variant data type.

Let's create a program to understand the dynamic array.

Dynamic_Arr.vb

Output:

VB.NET Dynamic Array

Adding New Element to an Array

When we want to insert some new elements into an array of fixed size that is already filled with old array elements. So, in this case, we can use a dynamic array to add new elements to the existing array.

Let us create a program to understand how we can add new elements to a dynamic array.

Dynamic_Arr1.vb

Output:

VB.NET Dynamic Array

In the above program, we have created a dynamic array Days as a String that executes the first three elements of Days such as Sunday, Monday, and Tuesday. we have also used a Preserve Keyword to keep the existing elements of an array with new elements in dynamic array Days.






Latest Courses