Dim array(9) As Integer ' Defines an array variable with 10 Integer elements (0-9).
Dim array = New Integer(10) {} ' Defines an array variable with 11 Integer elements (0-10)
'using New.
Dim array As Integer() = {1, 2, 3, 4} ' Defines an Integer array variable and populate it
'using an array literal. Populates the array with
'4 elements.
ReDim Preserve array(10) ' Redefines the size of an existing array variable preserving any
'existing values in the array. The array will now have 11 Integer
'elements (0-10).
ReDim array(10) ' Redefines the size of an existing array variable discarding any
'existing values in the array. The array will now have 11 Integer
'elements (0-10).
All arrays in VB.NET are zero-based. In other words, the index of the first item (the lower bound) in a VB.NET array is always 0
. Older versions of VB, such as VB6 and VBA, were one-based by default, but they provided a way to override the default bounds. In those earlier versions of VB, the lower and upper bounds could be explicitly stated (e.g. Dim array(5 To 10)
. In VB.NET, in order to maintain compatibility with other .NET languages, that flexibility was removed and the lower bound of 0
is now always enforced. However, the To
syntax can still be used in VB.NET, which may make the range more explicitly clear. For instance, the following examples are all equivalent to the ones listed above:
Dim array(0 To 9) As Integer
Dim array = New Integer(0 To 10) {}
ReDim Preserve array(0 To 10)
ReDim array(0 To 10)
Nested Array Declarations
Dim myArray = {{1, 2}, {3, 4}}