O'Reilly logo

Learning C# 2005, 2nd Edition by Brian MacDonald, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 least flexible of the five standard collections used in C# 2005:

  • Array

  • List

  • Stack

  • Queue

  • Dictionary

This chapter will introduce each of the latter four collections, and will show how the new feature generics are 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 like the ability to be used in a foreach loop or to access their members using an indexer:

    Employee joe = MyCompany[EmployeeID]

Generics

Until generics, all the collection classes (ArrayList, Stack, and Queue) were defined to hold objects of type Object (the root class). Thus, you could add integers and strings to the same class, and when you took items out of the collection, you had to cast them to their “real” type. This was ugly, and it was error-prone (the compiler could not tell if you had a collection of integers and added a string).

With generics, the designer of the class (the person who creates the Stack class) can say, “This class will hold only one type, and that type will be defined by the developer who makes an instance of this class.”

The user of the generic Stack class defines an instance of the Stack and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required