26.2. Collections OverviewAll the collection classes in the .NET Framework implement some combination of the collection interfaces. These interfaces declare the operations to be performed on various types of collections. Figure 26.1 lists some of the interfaces of the .NET Framework collections. All the interfaces in Fig. 26.1 are declared in namespace System. Collections and have generic analogues in namespace System. Collections.Generic. Implementations of these interfaces are provided within the framework. You may also create your own custom implementations.
Earlier versions of the .NET Framework provided the collection classes in the System.Collections and System.Collections.Specialized namespaces. These classes stored and manipulated Object references. You could store any Object in a collection. One inconvenient aspect of storing Object references occurs when retrieving them from a collection. An application normally needs to process specific types of objects, so the Object references obtained from a collection typically need to be downcast to an appropriate type. The .NET Framework 2.0 now also includes the System.Collections.Generic namespace, which uses the generics capabilities we introduced in Chapter 25. Many of these new classes are simply generic counterparts of the classes in the System.Collections namespace. This means that you can specify the exact type that will be stored in a collection. You also receive the benefits of compile-time type checkingthe compiler ensures that you are using appropriate types with your collection and, if not, issues compile-time error messages. Also, once you specify the type stored in a collection, any item you retrieve from the collection will have the correct type. This eliminates the need for explicit type casts that can throw InvalidCastExceptions at execution time if the referenced object is not of the appropriate type. This also eliminates the overhead of explicit casting, improving efficiency. In this chapter, we demonstrate six collection classesArray, ArrayList, Stac, Hashtable, generic SortedDictionary and generic LinkedListplus built-in array capabilities. Namespace System.Collections provides several other data structures, including BitArray (a collection of true/false values), Queue and SortedList (a collection of keyvalue pairs that are sorted by key and can be accessed either by key or by index). Figure 26.2 summarizes many of the collection classes. We also discuss the IEnumerator interface. Collection classes can create enumerators that allow you to walk through the collections. Although these enumerators have different implementations, they all implement the IEnumerator interface so thatthey can be processed polymorphically. As we will soon see, the For Each statement is simply a convenient notation for using an enumerator. In the next section, we begin our discussion by examining enumerators and the collections capabilities for array manipulation.
|