- An array is like a Collection. It's a sequence of variables that share a name and are distinguished
by number. Arrays can be of 1 or more dimensions, but for now we'll just look at 1-dimensional arrays.
- To declare an array in VB.NET, use parentheses, with the maximum index inside the parenthesis. For
example, here is a declaration for an array of 5 Integers called myArray, and a loop to store the numbers
1 through 5 in its elements (indexed 0 through 4):
Dim i As Integer
Dim myArray(4) As Integer
For i = 0 To 4
myArray(i) = i + 1
Next i
- The maximum index of an array is returned by the method GetUpperBound, which requires an
integer argument specifying which dimension's upper bound is desired (starting from 0). So the beginning
of the For loop above could be re-written as:
For i = 0 To myArray.GetUpperBound(0)
- Arrays in .NET are really reference variables (like in Java). So you my declare an array reference
variable without actually allocating the array. Then later you can make that variable refer to an array.
For example, the following code could follow the code above:
Dim arrayRef() As Integer 'could be written: Dim arrayRef As Integer()
Dim strAnswer As String
' The following line would throw a NullReferenceException:
' Object reference not set to an instance of an object.
' i = arrayRef.GetUpperBound(0)
arrayRef = myArray 'both reference variables refer to same array
myArray(0) = 10
For i = 0 To arrayRef.GetUpperBound(0)
strAnswer &= CStr(arrayRef(i)) & " "
Next i
MsgBox(strAnswer) 'Displays "10 2 3 4 5"
- ReDim is used to specify the size for an Array if it was previously just a Nothing reference.
(Such as arrayRef above before it was assigned to myArray)
- To expand the size of an array, use ReDim with "Preserve" optionally specifying that the original
elements should be retained, e.g.:
ReDim Preserve myArray(8)
- Multi-dimensional arrays are specified with commas separating their indexes, e.g.:
Dim TwoDArray(5, 5) As Integer
Dim j As Integer
For i = 0 To TwoDArray.GetUpperBound(0)
For j = 0 To TwoDArray.GetUpperBound(1)
TwoDArray(i, j) = i * j
Next j
Next i
strAnswer = ""
For i = 0 To 5
strAnswer &= CStr(TwoDArray(i, i)) & " "
Next i
MsgBox(strAnswer) 'Displays "0 1 4 9 16 25"