Chapter 14. Generics and Collections

You saw in Chapter 10 that arrays are useful for when you have a group of objects of the same type, and you need to treat them as a group—as a collection. Arrays are the simplest collection in C#, and they’re the one that you learn when you’re starting out, to get you accustomed to thinking about collections. However, arrays are probably the least flexible of the standard collections used in C#, because you have to define the size of an array when you create it. C# actually has a bunch of collection classes, but the five most commonly used are:

  • Array

  • List

  • Stack

  • Queue

  • Dictionary

This chapter will introduce each of the latter four collections, and will show how the C# feature called generics is used to make these collections type-safe—and why type safety is important.

You can also create classes that act like collections, and you can provide support for your collection classes so that they support some or all of the behavior expected of collections, such as the ability to be used in a foreach loop or to access their members using an indexer:

Employee joe = MyCompany[EmployeeID]

Get Learning C# 3.0 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.