6 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 www.wrox.com/go/professionalcsharp6 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

Generics are an important concept of not only C# but also .NET. Generics are more than 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. You can find generics with delegates in Chapter 9, “Delegates, Lambdas, and Events.” ...

Get Professional C# 6 and .NET Core 1.0 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.