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 type, we create one generic Garage class:

public class Garage<T>
{
	public T[] Vehicles { get; private set; }

	public Garage(int garageSize)
	{
		Vehicles = new T[garageSize];
	}
}

It’s not quite finished:

// A garage that stores integers instead of vehicles???
var myStrangeGarage = new Garage<int>(20);

Our class doesn’t filter and accepts any type as a parameter. We should only be able to use classes that inherit from Vehicle because the garage stores vehicles.

To solve our issue, we can use constraints:

public class Garage<T> where T : Vehice
{
}

The where T : Vehicle statement after the class declaration says that T can only be a Vehicle or any class that derives from Vehicle. If we provide a class that doesn’t meet this requirement, our code won’t compile:

Get hands-on with 1200+ tech skills courses.