Visual Basic Collection Class
A collection is a way of grouping a set of related items. Many different types of collections exist. Predefined collections are used in Visual Basic applications for many purposes, for example the Control.ControlCollection on a Form, returned by the form's Controls property. You can also create your own collections to organize and manipulate objects.
Collections are a good way to keep track of objects that your application might need to dynamically create and destroy. The following code fragment shows how you can use the Add method of a Visual Basic Collection object to keep a list of widget objects the user has created.
' Declare and create the Collection object. Public widgetColl As New Microsoft.VisualBasic.Collection() ' Create a new widget and add it to the widgetColl collection. Private Sub makeAWidget() Dim tempWidget As New widget() widgetColl.Add(tempWidget) End Sub
In the preceding example, the widgetColl collection organizes and exposes all of the widget objects created through the makeAWidget procedure. You can retrieve object references to each widget through the index of the collection. The size of the collection is adjusted automatically as each new widget object is added. You can use the For Each...Next Statement (Visual Basic) to iterate through the collection. If you want to give the widget object a key by which it can be retrieved, you can supply a text string as the second parameter of the Add method.
The Visual Basic Collection object stores all its elements as type Object, so you can add an item of any data type. There is no safeguard against inappropriate data types being added. To avoid this limitation, you can use the generic collections of the System.Collections.Generic namespace. For more information, see How to: Create a Collection of Objects (Visual Basic).
The New Operator (Visual Basic) keyword in the declaration for the variable widgetColl causes a Collection object to be created when control passes to the declaration statement. Because Collection is a class, rather than a value type, you must create an instance of it and keep a reference to that instance in a variable. This instance is a Visual Basic Collection object.
Like any other object, a Collection object is marked for garbage collection (GC) when the last variable that contains a reference to it is set to Nothing (Visual Basic) or goes out of scope. All the object references it contains are released when it is reclaimed by garbage collection. For this reason, the variable widgetColl in the preceding example is declared in the parent class, so that it exists throughout the life of the program.
A collection maintains references to the objects it controls but does not contain the objects themselves. Therefore, destroying a Collection object does not destroy the objects it controls. Each individual object that had been an element of the collection continues to exist until it is individually marked for garbage collection.
The basic services of adding, deleting, and retrieving elements from a collection depend on keys and indexes. A key is a String value. It could be a name, a driver's license number, a phone number, or simply an integer converted to a string. The Add method allows you to associate a key with an element, as described in How to: Add, Delete, and Retrieve Items of a Collection (Visual Basic).
An index in the Collection class is an integer between 1 and the number of items in the collection. The Count property returns the current number of items. You can control the initial value of an item's index by using the Before or After parameters when you call Add, but the index value could change as other items are added and deleted. For more information, see Add.
You can pass a key value to the Contains method to test whether a collection contains an element with that key. You can retrieve an element by passing either its key or its index to the Item property.
You can use index values and the Item property to iterate over the items in a collection, or you can use the For Each...Next Statement (Visual Basic). The following example shows two ways to give all the employees in a collection of employee objects a 10 percent raise, assuming that the variable employeesColl contains a reference to a Collection object.
Option Strict On ' The following alternative uses the Count and Item properties. Dim emp As employee For counter As Integer = 1 To employeesColl.Count emp = CType(employeesColl.Item(counter), employee) emp.payRate *= 1.1 Next counter ' The following alternative uses the For Each...Next statements. For Each emp As employee In employeesColl emp.payRate *= 1.1 Next emp
However, if you have added one or more elements to employeesColl that are not of type employee, the For Each loop throws an ArgumentException exception at run time.
Data Type of Elements
A Visual Basic Collection object stores each item with data type Object. Therefore, the range of data types you can add to a Collection object is the same as the range of data types you can store in an Object variable. This includes standard data types, objects, and arrays, as well as user-defined structures and class instances.
Because the Collection object stores each item as an Object, the Item property returns an Object value. To use the item in your code, you must typically convert from Object to the run-time data type of the item. The way you do this depends on the setting of the type checking switch in the Option Strict Statement.
Implicitly Converting from Object
If Option Strict is Off, you can implicitly convert an element of the Collection to its appropriate data type, as shown in the following example.
Option Strict Off Dim sampleColl As New Microsoft.VisualBasic.Collection() Dim sampleString As String = "This is a string" Dim aString As String sampleColl.Add(sampleString) ' The following statements convert the collection item to a string. Try aString = sampleColl.Item(1) Catch ex As Exception ' Insert code to run if the collection item cannot be converted to String. End Try
Explicitly Converting from Object
If Option Strict is On, you must explicitly convert from Object to the run-time data type of the element. To obtain an element from Item in this way, you can use the CType Function (Visual Basic) to perform the conversion, as shown in the following example.
Option Strict On Dim sampleColl As New Microsoft.VisualBasic.Collection() Dim sampleString As String = "This is a string" Dim aString As String sampleColl.Add(sampleString) ' The following statements convert the collection item to a string. Try aString = CType(sampleColl.Item(1), String) Catch ex As Exception ' Insert code to run if the collection item cannot be converted to String. End Try
The properties and methods of the Collection object provide only the most basic services for collections. For example, the Add method cannot check the type of an element being added to a collection, which you might want to do to ensure that the collection contains only one kind of element. If you can ensure this in the Add method, you have a strongly-typed collection, and you do not have to convert the return from the Item property to its run-time data type. This improves your performance.
You can provide more robust functionality — and additional properties, methods, and events — by creating your own collection class, as described in How to: Define Collections in Your Classes (Visual Basic).