O'Reilly logo

Professional C# 2012 and .NET 4.5 by Morgan Skinner, Karli Watson, Jay Glynn, Bill Evjen, Christian Nagel

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 5

Generics

WHAT’S IN THIS CHAPTER?

  • An overview of generics
  • Creating generic classes
  • Features of generic classes
  • Generic interfaces
  • Generic structs
  • Generic methods

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

The wrox.com code downloads for this chapter are found at http://www.wrox.com/remtitle.cgi?isbn=1118314425 on the Download Code tab. The code for this chapter is divided into the following major examples:

  • Linked List Objects
  • Linked List Sample
  • Document Manager
  • Variance
  • Generic Methods
  • Specialization

GENERICS OVERVIEW

Since the release of .NET 2.0, .NET has supported generics. Generics are not just a part of the C# programming language; they are deeply integrated with the IL (Intermediate Language) code in the assemblies. With generics, you can create classes and methods that are independent of contained types. Instead of writing a number of methods or classes with the same functionality for different types, you can create just one method or class.

Another option to reduce the amount of code is using the Object class. However, passing using types derived from the Object class is not type safe. Generic classes make use of generic types that are replaced with specific types as needed. This allows for type safety: the compiler complains if a specific type is not supported with the generic class.

Generics are not limited to classes; in this chapter, you also see generics with interfaces and methods. Generics with delegates can be found in Chapter 8, “Delegates, Lambdas, ...

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