Dynamic Array In VB.NET
What is Dynamic Array?
Explanation
Dynamic Array
Dynamic arrays are array that are declared using a
Dim statement with blank parenthesis initially and are dynamically
allocated dimensions using the
Redim statement.
Example:
Module Module1
Sub Main()
Dim a() As Integer = {2, 2}
Dim i, j As Integer
Console.WriteLine("Array before Redim")
For i = 0 To a.GetUpperBound(0)
Console.WriteLine(a(i))
Next
ReDim Preserve a(5)
Console.WriteLine("Array after Redim")
For j = 0 To a.GetUpperBound(0)
Console.WriteLine(a(j))
Next
Console.ReadLine()
End Sub
End Module
Result:
Array before Redim
2
2
Array after Redim
2
2
0
0
0
0
Description:
In the above Dynamic Array example, the array
a initially declared with 2 elements, then using the
ReDim statement a dimension of
5 is assigned. The
Preserve keyword is used to preserve the
existing elements intact.