Chapter 15 Generics

What’s in This Chapter

  • Defining generic classes and methods
  • Constraining generic types
  • Instantiating generic classes
  • Using generic collection classes
  • Defining generic extension methods

Wrox.com Downloads for This Chapter

Please note that all the code examples for this chapter are available as a part of this chapter’s code download on the book’s website at www.wrox.com/go/csharp5programmersref on the Download Code tab.

Chapter 11, “OOP Concepts,” describes a class as like a blueprint or cookie cutter for creating objects. After you define a class, you can use it to create any number of objects with similar general characteristics but different details.

Similarly, a generic is like a cookie cutter for creating classes. After you define a generic, you can use it to create any number of classes that have similar features.

For example, the System.Collections.Generic namespace described in the preceding chapter defines a generic List class. That class lets you create lists of strings, lists of integers, lists of Employee objects, or lists of just about anything else.

This chapter explains how you can define and use your own generic classes.

Advantages of Generics

A generic class takes one or more data types as parameters. When you create an instance of a generic class, those parameters are filled in with specific data types such as string, int, or Employee. Tying the class to specific data types gives it several advantages over nongeneric classes:

  • Strong typing ...

Get C# 5.0 Programmer's Reference 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.