Creating Arrays of Objects


 
You declare and use arrays of an object type just as you would declare and use an array of any data type. The members of this array can be retrieved by their index, and can be manipulated as any object of this type would be. Arrays also have built-in functionality for searching and sorting that can be accessed through the array variable. For more information on these methods, see Array Class.

To create an array of objects

  1. Declare the array as shown in the sample code below. Because arrays are zero-based, they contain one member more than the upper bound you declare.

    Dim x(10) As Widget   ' Contains 11 members, from x(0) to x(10).
     
  2. Instantiate each member of the array, or assign each member a reference to an already existing object. An example of each approach is shown below:

    ' Instantiates each member of an array by using a loop.
    Dim q As Integer
    For q = 0 to 10
       x(q) = New Widget()
    Next

    ' Assigns a member of an array a reference to an existing object.
    Dim myWidget As New Widget()
    x(0) = myWidget
    x(1) = myWidget

    Note that you can assign the different members of the array references to the same object.