Chapter 4

Flexible Typing with Generics

WHAT’S IN THIS CHAPTER?

  • Generic functions, classes, and other elements
  • Constraints
  • Covariance and contravariance

The .NET type system has a feature called generics. With the help of this feature, certain pieces of type information can be extended by type parameters. In .NET, classes, methods, interfaces, and delegates can be generic.

One of the common examples of the use of generics is a container class, like a list. In an object oriented language, you can either write a List class to work with elements of a particular type (perhaps you create a ListElement for the purpose) or use a base class that is so general purpose that it allows users of the List type to add elements of arbitrary types (in .NET, System.Object comes to mind). Both of these approaches have disadvantages. Using the all-purpose base class allows the addition of potentially incompatible elements to the list, and using a particular special purpose class for the elements only defers the problem because the actual type must be encapsulated in the end.

Generics provide a solution to this issue. The List class is created to have a type parameter, and when instances are created, the type parameter is resolved so that any actual instance of the List class works with a particular type (and those derived from it).

Generally, a generic type G is written to work with one or more other types — O1, O2, and so on — but the idea is that the implementation of G doesn’t actually need ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects 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.