O'Reilly logo

C# 5.0 Programmer's Reference by Rod Stephens

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 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 ...

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