Chapter 12

Generics

WHAT YOU WILL LEARN IN THIS CHAPTER

  • What generics are
  • How to use some of the generic classes provided by the .NET Framework
  • How to define your own generics
  • How variance works with generics

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

You can find the wrox.com code downloads for this chapter at www.wrox.com/remtitle.cgi?isbn=9781118314418 on the Download Code tab. The code is in the Chapter 12 download and individually named according to the names throughout the chapter.

One of the (admittedly few) criticisms leveled against the first version of C# was its lack of support for generics. Generics in C++ (known as templates in that language) had long been regarded as an excellent way of doing things, as they enabled a single type definition to spawn a multitude of specialized types at compile time and thus save a lot of time and effort. For whatever reason, generics didn’t quite make it into the first release of C#, and the language suffered because of it. Perhaps it was because generics are often seen as being quite difficult to get a handle on, or maybe it was decided that they weren’t necessary. Fortunately, generics joined the party in version 2.0 of C#. Even better, they aren’t very difficult to use, although they do require a slightly different way of looking at things.

This chapter begins by looking at what generics are. You learn about generics in fairly abstract terms at first, because learning the concepts behind generics is crucial to being able to use ...

Get Beginning Visual C# 2012 Programming 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.