O'Reilly logo

Professional C# 2005 by Allen Jones, 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 10. Generics

One of the biggest changes of the C# language and the CLR is the introduction of generics. With .NET 1.0, creating a flexible class or method that should use classes that are not known at compile time must be based on the Object class. With the Object class, there's no type safety during compile time. Casting is necessary. Also, using the Object class for value types has a performance impact.

.NET 2.0 supports generics. With generics the Object class is no longer necessary in such scenarios. 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 a great feature, especially with collection classes. Most of the .NET 1.0 collection classes are based on the Object type. .NET 2.0 offers new collection classes that are implemented as generics.

Generics are not limited to classes; in this chapter, you also see generics with delegates, interfaces, and methods.

This chapter discusses the following:

  • Generics overview

  • Generic collection classes

  • Creating custom generic classes

  • Generic methods

  • Generic delegates

  • Other generic framework types

Overview

Generics are not a completely new construct; similar concepts exist with other languages. For example, C++ templates can be compared to generics. However, there's a big difference between C++ templates and .NET generics. With C++ templates the source code of the template is required ...

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