VB.net Dynamic Array
VB.net Dynamic Array
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.
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.
Also, if we want to store multiple data types in an array, we have to use a Variant data type.
Dynamic_Arr.vb
Imports System
Module Dynamic_Arr
Sub Main()
'Declaration and Initialization of String Array Days()
Dim Days(20) As String
' Resize an Array using the ReDim Statement
ReDim Days(6)
Days(0) = "Sunday"
Days(1) = "Monday"
Days(2) = "Tuesday"
Days(3) = "Wednesday"
Days(4) = "Thursday"
Days(5) = "Friday"
Days(6) = "Saturday"
Output:
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
Imports System
Module Dynamic_arr1
Sub Main()
'Declaration and Initialization of String Array Days()
Dim Days() As String
' Resize an Array using the ReDim Statement
ReDim Days(2)
Days(0) = "Sunday"
Days(1) = "Monday"
Days(2) = "Tuesday"
Console.WriteLine(" Before Preserving the Elements")
For i As Integer = 0 To Days.Length - 1
Console.WriteLine("Days Name in [{0}] index is {1}", i, Days(i))
Next
Console.WriteLine()
Output:
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.