Managing Your Objects with Collections (Visual Basic)
Collections provide an ideal way to manage a variety of objects. You can add and remove objects from a collection, retrieve them based on an index or a key, and use the For Each...Next Statement (Visual Basic) to iterate through the items in your collection.
However, the very flexibility of collections can undermine the robustness of your classes. For example, the collection provided by Visual Basic 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, and when you access an element, you must convert it from Object to the desired data type.
The .NET Framework provides several alternatives to the Visual Basic collection. The System.Collections namespace contains collection classes with specific functionality, such as a queue or a sorted list, and the System.Collections.Specialized namespace contains collection classes of specialized nature, such as HybridDictionary.
To avoid the disadvantages of elements of type Object, you can use the generic collections of the System.Collections.Generic namespace. These collections provide type safety and allow you to limit the elements of a collection to only one specific data type.
There are three general approaches you can take to implementing object management using collections. Consider an application that defines a widgetRepository class, which organizes and exposes widget objects to client components. To implement widgetRepository with a collection, you can use one of the following strategies.
Use a Collection Class. In the widgetRepository class, declare a widgetsColl variable as an instance of the Collection class or of one of the classes in the System.Collections, System.Collections.Generic, or System.Collections.Specialized namespaces. Make the variable public, and use the New Operator (Visual Basic) keyword to create an instance of the collection. For more information, see How to: Define Collections in Your Classes (Visual Basic).
Inherit a Collection Base Class. Implement your own widgetsColl class by inheriting from the CollectionBase class. In the widgetRepository class, define an instance of the widgetsColl class and a property that returns that instance. For more information, see How to: Define Collections in Your Classes (Visual Basic).
Write the Collection Yourself. Implement collection functionality in the widgetRepository class by writing the appropriate classes and procedures. This approach is most useful if you need collection functionality in your class but cannot inherit from any of the existing collection classes. This could be possible, for example, in the rare case that your class needed to inherit from a class other than a collection class. Because it cannot inherit from more than one class, you would have to define and implement collection members.