Udostępnij za pośrednictwem


Managing Groups of Objects in Visual Basic

For many applications, you want to be able to create and manage groups of related objects. There are two ways to group objects: by creating arrays of objects, and by creating collections of objects.

Arrays of Objects

Arrays are relatively inflexible structures. If you want to change the size of the array at run time, you must use the ReDim Statement (Visual Basic) to redeclare it. All elements of the array must be of the same type. On the other hand, arrays allow you to process all your elements sequentially, and you can have empty elements of an array. For these reasons, arrays are most useful for creating and working with a fixed number of strongly-typed objects.

For more information, see How to: Create an Array of Objects (Visual Basic).

Collections of Objects

Collections provide a more flexible way of working with groups of objects. A collection is a class, so you must declare a new collection before you can add elements to that collection. Unlike arrays, the group of objects you work with can grow and shrink dynamically as the needs of the application change. You can assign a key to any object that you put into a collection so that you can retrieve it and manipulate it based on that key.

You can create a generalized collection from the Collection class. If you want a specific functionality in a collection, for example a dictionary or a linked list, you can create it from one of the classes in the System.Collections namespace of the .NET Framework. Even more specialized collection classes are available in the System.Collections.Specialized namespace.

If your collection is limited to elements of only one data type, you can use one of the classes in the System.Collections.Generic namespace. A generic collection enforces type safety so that no other data type can be added to it. When you retrieve an element from a generic collection, you do not have to determine its data type or convert it.

For more information, see How to: Create a Collection of Objects (Visual Basic).

See Also

Tasks

How to: Add, Delete, and Retrieve Items of a Collection (Visual Basic)

Reference

System.Collections

System.Collections.Generic

System.Collections.Specialized

Concepts

Collections in Visual Basic

Visual Basic Collection Class

Other Resources

Arrays in Visual Basic

Objects and Classes in Visual Basic