Chapter 10

Collections

In Chapter 5, “Arrays,” you read information about arrays and the interfaces implemented by the Array class. The size of arrays is fixed. If the number of elements is dynamic, you should use a collection class.

List<T> and ArrayList are collection classes that can be compared to arrays. But there are also other kinds of collections: queues, stacks, linked lists, and dictionaries.

This chapter shows you how to work with groups of objects. It takes a close look at these topics:

  • Collection interfaces and types
  • Lists
  • Queues
  • Stacks
  • Linked lists
  • Sorted lists
  • Dictionaries
  • Lookups
  • HashSets
  • Bit arrays
  • Performance

Collection Interfaces and Types

Collection classes can be grouped into collections that store elements of type Object and generic collection classes. Previous to CLR 2.0, generics didn’t exist. Now the generic collection classes usually are the preferred type of collection. Generic collection classes are type-safe, and there is no boxing if value types are used. You need object-based collection classes only if you want to add objects of different types where the types are not based on each other, for example, adding int and string objects to one collection. Another group of collection classes is collections specialized for a specific type; for example, the StringCollection class is specialized for the string type.

You can read all about generics in Chapter 9, “Generics.”

Object-type collections are located in the namespace System.Collections; generic collection ...

Get Professional C# 2008 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.