DekGenius.com
[ Team LiB ] Previous Section Next Section

Chapter 27. System.Collections

The System.Collections namespace provides basic functionality for collections of objects. It defines interfaces, base classes, and implementations for collections such as dictionaries, sorted lists, queues, and stacks. The base classes can also be extended to create specialized collection types. However, the System.Collections.Specialized namespace contains a set of extended collection types based on this namespace, so check there before creating your own types.Figure 27-1 and Figure 27-2 show the types in this namespace.

On first observation, the design of these collections seems somewhat awkward—for example, why does a "list" seem to be broken into two pieces: the IList interface and the ArrayList implementation? On top of this, the namespace defines a number of other interfaces, such as IEnumerable and IEnumerator, that seem unnecessary.

In fact, the design of the collection types in this namespace is quite similar to the designs of other container libraries such as the STL (Standard Template Library) in C++ and the Java Collections library in JDK 1.2. By separating the interface of a collection type (the concept of "list-ness" or "dictionary-ness") from the actual implementation, you are free to assume only the absolute minimum about the actual implementation used, and instead focus only on what is needed in order to carry out the work. For example, C#'s foreach construct works by silently using the IEnumerable interface to obtain an object that inherits the IEnumerator interface. Thus, a programmer could, if desired, create a custom type (perhaps modeling a hand of cards) that acts just as any other collection class does. Alternatively, the iterator (the type that inherits from IEnumerator) could be a "smart" iterator, knowing how to walk through (or skip past) types in the container itself. All this is possible solely because the interface is separated from the implementation; it is decoupled.

Figure 27-1. Collection types implementing ICollection and IEnumerable
figs/csn2_2701.gif
Figure 27-2. More types from the System.Collections namespace
figs/csn2_2702.gif
    [ Team LiB ] Previous Section Next Section