#1,032 – Requiring Generic Type Parameters to Be a Reference or Value Type
February 13, 2014 2 Comments
By default, when you specify a type parameter in a generic class, the type can be any .NET type. There are times, however, when you’d like to constrain the type in some ways, for example requiring that the type be either a reference type or a value type.
To require a type argument to represent a reference type, use the class keyword:
public class PileOf<T> where T : class
To require a type argument to represent a non-nullable value type, use the struct keyword:
public class PileOf<T> where T : struct
You may want to use one of these constraints when your generic type includes code that will only work on a reference type or on a value type.