Bagikan melalui


How to: Create an Array of Objects (Visual Basic)

Every object is a reference type. You declare and use an array of a reference type just as you would declare and use an array of any data type. The elements of an object type array can be retrieved by their index and can be manipulated as any object of the given 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.

To create an array of objects

  1. Declare the array as shown in the following example. Because arrays are zero-based, they contain one element more than the upper bound you declare.

    Dim x(10) As widget
    ' x now contains 11 elements of type widget, x(0) through x(10).
    
  2. Create each element of the array, or assign to each element a reference to an already existing object. The following example demonstrates this.

    ' Create each element of an array by using a loop.
    For q As Integer = 0 To 10
        x(q) = New widget()
    Next q
    ' Assign a reference to an existing object to two array elements.
    Dim specialWidget As New widget()
    x(0) = specialWidget
    x(1) = specialWidget
    

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

See Also

Tasks

How to: Create a Collection of Objects (Visual Basic)

Concepts

Managing Groups of Objects in Visual Basic

Value Types and Reference Types

Other Resources

Arrays in Visual Basic