Default Constructor Constraints
If you need to instantiate a new object of the generic type specified by a type parameter within a generic class, you can apply a default constructor constraint. This type of constraint prevents the class from being instantiated for classes that do not include a public parameterless constructor. To apply such a constraint to the Pair class, modify the class's declaration as follows:
public class Pair<T> where T : new()
You could now include methods that create new T instances, such as:
public T InstantiateNew()
{
return new T();
}
Value / Reference Type Constraints
The third type of constraint is the value / reference type constraint. This type of constraint ensures that type parameters are always either value types or reference types. To force the Pair class to only accept reference types, the following definition could be used:
public class Pair<T> where T : class
To ensure that the type parameter is always a non-nullable value type, the following definition would be used:
public class Pair<T> where T : struct
11 April 2010