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 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.