#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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: