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
Since the release of .NET 2.0, .NET has supported generics. Generics are not just a part of the C# programming language, but are also 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 code is using the Object
class. However, 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, and Events."
GENERICS OVERVIEW
Generics are not a completely new construct; similar concepts exist with other languages. For example, C++ templates have some similarity 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 when a template is instantiated with a specific type. Unlike C++ templates, generics are not ...
Get Professional C# 4 and .NET 4 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.