Keeping Stuff in C# Collection Classes
Part of the C# 5.0 All-in-One For Dummies Cheat Sheet
Many variables are for storing one thing, like a number or a sentence. An object can have a lot of properties, storing a lot of information about a single concept. Sometimes, though, you just have to keep track of a big list of stuff. That’s where the collection classes come in.
The collection classes in C# are awesome because they can help you keep a list of items, or a group of keys and values, and provide searching, proctoring, and general maintenance tools for free. That’s a lot easier than writing the two hundredth ‘sort customers by last name’ method this month.
C# has basic collection classes, generic collection classes, and concurrent collection classes. These last ones are for thread safe operations in a multiprocessor environment. All of these collection classes are useful if you know where and when to use them.
Regular collections store untyped stuff for you. If you don’t know exactly what you’re going to store, regular collections are for you. Most everything in these classes are stored as Object.
|ArrayList||This is just a straightforward collection of objects whose size is initially declared, and that size is increased as needed (but not decreased).|
|HashTable||Just a two-column table of keys and values, where the pairs are linked for sorting a retrieval.|
|Queue||A first in, last out (FIFO) list of items. Great for storing program process stuff.|
|Stack||Like a Queue, but Last In First Out (LIFO).|
C# 2.0 introduced generic collections. Generic collections allow you to store typed collections of items, as declared at runtime.
|Dictionary<TKey, TValue>||Just a HastTable, except typed, so you don’t have to store Object, Object. TKey and TValue are types, so you can store a list of <Int32, String> if you want.|
|List<T>||This is the new Array. It’s a typed list of items. By far, the most common collection class used. It’s the default. If you need a list of people, it’s a List<Person>.|
|Queue<T>||Similar to the untyped Queue, but, well, typed!|
|SortedList<TKey, Value>||This awesome Dictionary implements IComparable so that it can be sorted.|
|Stack<T>||Just like the untyped Stack, except typed.|
Concurrent collection classes
Finally, the Concurrent classes make sure that the objects you store in a list are available in any memory space, no matter what processor. It’s a bigger deal than you think.
|BlockingCollection<T>||It’s a thread-safe class that will prevent one thread from altering a field that is accessible by another thread. Brilliant stuff, really.|
|ConcurrentDictionary<TKey, TValue>||Speaking of brilliant, this set of key/value pairs can be accessed by multiple threads.|
|ConcurrentQueue<T>||Remember that FIFO stack? Yeah. This one is generic AND thread safe.|
|ConcurrentStack<T>||The orchestrated collections are useful. They’re beneficial for memory, for one thing. Anyway, this one is LIFO and thread-safe, too.|