O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required