...

/

Constraining the Type Parameters

Constraining the Type Parameters

Understand possible constraints that can be applied to type parameters.

Introduction

A generic can take any type parameter we provide. Sometimes, though, we may want to add some constraints.

Consider a set of classes: Vehicle (abstract base class), Car, Truck (both inherit from Vehicle), and the Garage class to hold our vehicles. Because there are two types of vehicles (Car and Truck), two types of garages are needed: one holds cars, and the other holds trucks.

Instead of creating two separate classes for each vehicle ...