#1,032 – Requiring Generic Type Parameters to Be a Reference or Value Type

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.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #1,032 – Requiring Generic Type Parameters to Be a Reference or Value Type

  1. Pingback: Dew Drop – February 13, 2014 (#1722) | Morning Dew

  2. Pingback: #1,035 – Summary of Type Parameter Constraints | 2,000 Things You Should Know About C#

Leave a comment