Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 182 ยท Collections

Non-Generic and Specialized Collections

Meet the pre-generics C# collections - ArrayList, Hashtable, BitArray, OrderedDictionary and NameValueCollection - see why generics replaced them, and learn how to migrate old code.

Before C# 2.0 (2005) there were no generics. Collections stored everything as object, so a list could hold numbers, strings and dates all at once, and the compiler could not tell you which one you would get back. Those classes still live in the base class library, in the namespaces System.Collections and System.Collections.Specialized. You will meet them in old code bases, in older tutorials, and in a few APIs (such as NameValueCollection in web code) that never moved on.

This lesson shows how the old collections work, why they were replaced, and what to use instead. You will not write new programs with most of them, but you need to be able to read them and migrate them safely.

Microsoft recommends the generic collections from System.Collections.Generic for all new code. The classic non-generic collections are not marked obsolete, but they are kept only for compatibility. See choosing the right collection for the modern picks.

ArrayList: the list that holds anything

ArrayList is the ancestor of List<T>. It grows automatically, supports Add, Insert, Remove, Contains, Sort and an indexer, but every item is an object.

C# ArrayList stores objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

There are two problems in that program. First, the bad cast (int)items[1] compiles without a warning and only fails when it runs. With a List<int> the compiler would have refused to let you add a string in the first place. Second, adding an int boxes it: the runtime allocates a small object on the heap to hold the number, and reading it back unboxes it. In a loop over a million numbers that means a million extra allocations. The lesson on boxing explains the cost in detail.

Hashtable: the old dictionary

Hashtable maps keys to values like Dictionary<TKey,TValue>, but both sides are object. Looking up a missing key returns null instead of throwing, and enumeration yields DictionaryEntry structs.

C# Hashtable lookups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The enumeration order of a Hashtable is not defined, so do not rely on the order your lines print in. The Dictionary version is also faster and uses less memory because it stores keys and values without boxing.

BitArray: a compact array of booleans

BitArray is the one classic collection that is still genuinely useful. It stores one bit per element instead of one byte, supports bitwise operations across the whole array, and has a fixed length you can change with Length. It is non-generic only in name: its items are always bool, so nothing is boxed.

C# BitArray as a set of flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

And, Or, Xor and Not change the array they are called on and return it, which is why the example copies evens first with new BitArray(evens). A sieve of Eratosthenes or a set of 10,000 on/off flags fits in about a kilobyte this way.

The specialized collections

System.Collections.Specialized holds small niche collections. Here is what each is for and what replaced it.

Type What it does Modern choice
ListDictionary Dictionary backed by a linked list; fast for fewer than about 10 items Dictionary<TKey,TValue>
HybridDictionary Starts as a ListDictionary, switches to a Hashtable when it grows Dictionary<TKey,TValue>
StringDictionary Case-insensitive keys, string values only Dictionary<string,string> with StringComparer.OrdinalIgnoreCase
OrderedDictionary Remembers insertion order and allows access by index OrderedDictionary<TKey,TValue> (new in .NET 9)
NameValueCollection One key, many string values (query strings, old config files) Dictionary<string, List<string>> or ILookup
StringCollection List of strings List<string>

The two you are most likely to meet are OrderedDictionary and NameValueCollection:

C# OrderedDictionary and NameValueCollection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

NameValueCollection is a hybrid: the indexer returns all values for a key joined by commas, while GetValues returns them as an array. It is still what some older ASP.NET APIs hand you for form and query data.

Why generics won

Generic collections fix every weakness shown above:

Problem with old collections How generics fix it
object items need casts, and wrong casts fail at run time The element type is part of the collection type; errors appear at compile time
Value types are boxed and unboxed List<int> stores ints directly in an array
Methods such as Sort take untyped IComparer Comparer<T> and lambdas are typed
Collections can hold a mix of types by accident A List<string> can only hold strings
foreach needs an explicit cast per item The loop variable is already the right type

A quick measurement shows the cost of boxing, even on a small run. Timings vary between machines, so look at the ratio, not the exact numbers:

C# ArrayList versus List of int

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Migrating old code

When you inherit code that uses the old types, work through these steps:

  1. Find what is really stored. If an ArrayList only ever contains strings, replace it with List<string>; the casts disappear and the compiler will point to each wrong Add.
  2. Replace Hashtable with Dictionary<TKey,TValue>. Change reads that expect null for a missing key to TryGetValue.
  3. Keep interop in mind. Some old APIs still require IList or ICollection. List<T> implements the non-generic IList too, so a typed list can be passed where an old one is expected.
  4. Use Cast<T>() or OfType<T>() at the boundary. When an old API returns a non-generic collection, these LINQ operators turn it into a typed IEnumerable<T> once, and the rest of your code stays typed.
C# Cast and OfType at the boundary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main compile-time weakness of ArrayList compared with List<T>?

    ArrayList holds object references, so any type can be added and every read needs a cast that is only checked at run time.
  2. 2. What happens when you read a key that does not exist from a Hashtable?

    Hashtable returns null for a missing key, which is easy to miss. Dictionary<TKey,TValue> throws KeyNotFoundException, or you can use TryGetValue.
  3. 3. Which classic collection is still a good choice because it stores one bit per element?

    BitArray packs booleans into bits and offers And, Or, Xor and Not over the whole array.
  4. 4. You receive an ArrayList from an old API and want only the int items as a typed sequence. What do you call?

    OfType<int>() filters to the items that are ints and returns IEnumerable<int>. Cast<int>() would throw on the first non-int item.

Summary

  • Non-generic collections (ArrayList, Hashtable) store object, which needs casts and boxes value types.
  • Their errors appear at run time, while generic collections catch them at compile time.
  • BitArray is still useful for compact boolean sets and bitwise operations.
  • OrderedDictionary, NameValueCollection and the other specialized types survive mainly for compatibility; OrderedDictionary<TKey,TValue> is the new generic option.
  • Migrate by finding the real element type, switching to List<T> or Dictionary<TKey,TValue>, and using OfType<T>() or Cast<T>() at old API boundaries.

Next: see how every collection fits together in IEnumerable, ICollection and IList, or jump ahead to choosing the right collection.