CHAPTER 9 COLLECTIONS AND GENERICS
Generic Constraint
Meaning in Life
where T : NameOfInterface
The type parameter must implement the interface specified by
NameOfInterface. You can separate multiple interfaces as a commadelimited list.
Unless you need to build some extremely type-safe custom collections, you might never need to use
the where keyword in your C# projects. Regardless, the following handful of (partial) code examples
illustrate how to work with the where keyword.
Examples Using the where Keyword
Begin by assuming that you have created a custom generic class, and you want to ensure that the type
parameter has a default constructor. This could be useful when the custom generic class needs to create
instances of the T because the default constructor is the only constructor that is potentially common to
all types. Also, constraining T in this way lets you get compile-time checking; if T is a reference type, the
programmer remembered to redefine the default in the class definition (you might recall that the default
constructor is removed in classes when you define your own):
// MyGenericClass derives from object, while
// contained items must have a default ctor.
public class MyGenericClass where T : new()
{
...
}
Notice that the where clause specifies which type parameter is being constrained, followed by a
colon operator. After the colon operator, you list each possible constraint (in this case, a default
constructor). Here is another example:
// MyGenericClass derives from object, while
// contained items must be a class implementing IDrawable
// and must support a default ctor.
public class MyGenericClass where T : class, IDrawable, new()
{
...
}
In this case, T has three requirements. It must be a reference type (not a structure), as marked with
the class token. Second, T must implement the IDrawable interface. Third, it must also have a default
constructor. Multiple constraints are listed in a comma-delimited list; however, you should be aware
that the new() constraint must always be listed last! Thus, the following code will not compile:
// Error! new() constraint must be listed last!
public class MyGenericClass where T : new(), class, IDrawable
{
...
}
If you ever create a custom generic collection class that specifies multiple type parameters, you can
specify a unique set of constraints for each, using separate where clauses:
356