ARRAYS

Visual Basic .NET provides two basic kinds of arrays. First, it provides the normal arrays that you get when you declare a variable by using parentheses. For example, the following code declares an array of Integers named “squares”:

Private Sub ShowSquaresNormalArray()
    Dim squares(10) As Integer
   
    For i As Integer = 0 To 10
        squares(i) = i * i
    Next i
   
    Dim txt As String = ""
    For i As Integer = 0 To 10
        txt &= squares(i).ToString & vbCrLf
    Next i
    MessageBox.Show(txt)
End Sub

The array contains 11 items with indexes ranging from 0 to 10. The code loops over the items, setting each one’s value. Next, it loops over the values again, adding them to a string. When it has finished building the string, the program displays the result.

INITIALIZING ARRAYS
You can initialize an array as in the following code:
Dim fibonacci() As Integer = {1, 1, 2, 3, 5, 8, 13, 21, 33, 54, 87}
If you have Option Infer turned on, you can omit the data type as in the following:
Dim numbers() = {1, 2, 3}
For more information on array initialization, see the section “Initializing Arrays” in Chapter 14, “Data Types, Variables, and Constants.”

The Visual Basic Array class provides another kind of array. This kind of array is actually an object that provides methods for managing the items stored in the array.

The following code shows the previous version of the code rewritten to use an Array object:

Private Sub ShowSquaresArrayObject() Dim squares As Array = Array.CreateInstance(GetType(Integer), 11) ...

Get Visual Basic 2012 Programmer's Reference now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.