|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
Collections as an Alternative to Arrays
Although collections are most often used for working with the, you can use a collection to work with any data type. In some circumstances, it can be more efficient to store items in a collection than in an array.
If you need to change the size of an array, you must use the. When you do this, Visual Basic creates a new array and releases the previous array for disposal. This takes execution time. Therefore, if the number of items you are working with changes frequently, or you cannot predict the maximum number of items you need, you might obtain better performance using a collection.
A collection, which does not have to create a new object or copy existing elements, can handle resizing in less execution time than an array, which has to use ReDim. But if the size does not change, or changes only rarely, an array is likely to be more efficient. As always, performance is highly dependent on the individual application. It is often worth your time to try both an array and a collection.
The .NET Framework also provides a variety of classes, interfaces, and structures for general and special collections. Theand namespaces contain definitions and implementations that include dictionaries, lists, queues, and stacks. The namespace provides many of these in generic versions, which take one or more type arguments.
If your collection is to hold elements of only one specific data type, a generic collection has the advantage of enforcing type safety. For more information on generics, see.
The following example uses the .NET Framework generic classto create a list collection of customer structures.
' Define the structure for a customer. Public Structure customer Public name As String ' Insert code for other members of customer structure. End Structure ' Create a module-level collection that can hold 200 elements. Public custFile As New List(Of customer)(200) ' Add a specified customer to the collection. Private Sub addNewCustomer(ByVal newCust As customer) ' Insert code to perform validity check on newCust. custFile.Add(newCust) End Sub ' Display the list of customers in the Debug window. Private Sub printCustomers() For Each cust As customer In custFile Debug.WriteLine(cust) Next cust End Sub
The declaration of the custFile collection specifies that it can contain elements only of type customer. It also provides for an initial capacity of 200 elements. The procedure addNewCustomer checks the new element for validity and then adds it to the collection. The procedure printCustomers uses a For Each loop to traverse the collection and display its elements.