Share via


Visual Basic Concepts

Creating Collections of Objects

Collections provide a useful way to keep track of objects. Unlike arrays, Collection objects don't have to be re-dimensioned as you add and remove members.

For example, you might want to keep track of every control that was dropped onto a particular control, and not allow any control to be dropped more than once. You can do this by maintaining a Collection that contains references to each control that has been dropped:

Private Sub List1_DragDrop(Source As VB.Control, _
X As Single, Y As Single)
   Dim vnt As Variant
   Static colDroppedControls As New Collection
   For Each vnt In colDroppedControls
      ' If the dropped control is in the collection,
      ' it's already been dropped here once.
      If vnt Is Source Then
         Beep
         Exit Sub
      End If
   Next
   ' Save a reference to the control that was dropped.
   colDroppedControls.Add Source
   ' Add the name of the control to the list box.
   List1.AddItem Source.Name
End Sub

This example uses the Is operator to compare the object references in the colDroppedControls collection with the event argument containing the reference to the dropped control. The Is operator can be used to test the identity of Visual Basic object references: If you compare two different references to the same object, the Is operator returns True.

The example also uses the Add method of the Collection object to place a reference to the dropped control in the collection.

Unlike arrays, Collections are objects themselves. The variable colDroppedControls is declared As New, so that an instance of the Collection class will be created the first time the variable is referred to in code. The variable is also declared Static, so that the Collection object will not be destroyed when the event procedure ends.

For More Information   See "Is Operator" in the Language Reference.

Properties and methods of the Collection object are discussed in "The Visual Basic Collection Object" later in this chapter.

To compare the code above with the code required to use arrays, see "Creating Arrays of Objects," earlier in this chapter.

To learn how to create more robust collections by wrapping the Collection object in your own collection class, see "Creating Your Own Collection Classes" later in this chapter.

"What You Need to Know About Objects in Visual Basic," earlier in this chapter, describes how objects are created and destroyed.