This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 2.0+

Generic Types

Microsoft introduced generics to the .NET framework with version 2.0. Generic programming allows highly reusable classes to be created without specifying the types that they operate upon. These types are only provided when the class is used.

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