Base Class Constraints

Not just interfaces can be used to constrain a type parameter to only those types that implement it; base classes can also be used to enforce a similar relationship. You can constrain a type parameter such that only subclasses of a specified base class can be used to instantiate the parameter:

class FruitMixer<T> where T : Fruit {    private readonly T[] _ingredients;    public FruitMixer(params T[] ingredients) {        _ingredients = ingredients;    }}

Enforcement of the constraint is similar to what we’ve seen with interfaces. The following works fine, for the obvious reason that every Jonagold is an Apple:

var appleMixer = new FruitMixer<Apple>(new Jonagold());

Notice that generics go hand ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.