Understanding Generics—The System.Collections.Generic Namespace
The System.Collections.Generic Namespace
Generic types are found sprinkled throughout the .NET 2.0 base class libraries; however, the System.Collections.Generic namespace is chock full of them (as its name implies). Like its nongeneric
counterpart (System.Collections), the System.Collections.Generic namespace contains numerous
class and interface types that allow you to contain subitems in a variety of containers. Not surprisingly,
the generic interfaces mimic the corresponding nongeneric types in the System.Collections namespace:
•ICollection<T>
•IComparer<T>
•IDictionary<K, V>
•IEnumerable<T>
•IEnumerator<T>
•IList<T>
■Note By convention, generic types specify their placeholders using uppercase letters. Although any letter (or word) will do, typically T is used to represent types, K is used for keys, and V is used for values.
The System.Collections.Generic namespace also defines a number of classes that implement
many of these key interfaces. Table 10-1 describes the core class types of this namespace, the interfaces they implement, and any corresponding type in the System.Collections namespace.
Table 10-1. Classes of System.Collections.Generic
| Generic Class | Nongeneric Counterpart in System.Collections | Meaning in Life |
Collection<T>
| CollectionBase
| The basis for a generic collection |
Comparer<T>
| Comparer
| Compares two generic objects for equality |
Dictionary<K, V>
| Hashtable
| A generic collection of name/value pairs |
List<T>
| ArrayList
| A dynamically resizable list of items |
Queue<T>
| Queue
| A generic implementation of a first-in, first-out (FIFO) list |
SortedDictionary<K, V>
| SortedList
| A generic implementation of a sorted set of name/value pairs |
Stack<T>
| Stack
| A generic implementation of a last-in, first-out (LIFO) list |
LinkedList<T>
| N/A | A generic implementation of a doubly linked list |
ReadOnlyCollection<T>
| ReadOnlyCollectionBase
| A generic implementation of a set of read-only items |
The System.Collections.Generic namespace also defines a number of "helper" classes and
structures that work in conjunction with a specific container. For example, the LinkedListNode<T> type represents a node within a generic LinkedList<T>, the KeyNotFoundException exception is raised
when attempting to grab an item from a container using a nonexistent key, and so forth.
As you can see from Table 10-1, many of the generic collection classes have a nongeneric counterpart
in the System.Collections namespace (some of which are identically named). Given that
Chapter 7 illustrated how to work with these nongeneric types, I will not provide a detailed examination
of each generic counterpart. Rather, I’ll make use of List<T> to illustrate the process of working with
generics. If you require details regarding other members of the System.Collections.Generic namespace,
consult the .NET Framework 2.0 documentation.
|

