#1,033 – Requiring a Generic Type Parameter to Have a Parameterless Constructor

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.

You can require that a type passed in as a type argument implement a public parameterless constructor by using the where keyword and specifying new().  The new() constraint tells the code that is constructing the type that it needs to only use types that have a parameterless constructor.

Without this constraint, you are not allowed to construct instances of the type passed in as a type parameter.  (The compiler will tell you to add the new() constraint).

With the constraint, your class might look like this:

    public class PileOf<T> where T : new()
    {
        private List<T> thePile;

        public PileOf()
        {
            thePile = new List<T>();

            // First element in list is a default T
            thePile.Add(new T());
        }
    }
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,033 – Requiring a Generic Type Parameter to Have a Parameterless Constructor

  1. Pingback: Dew Drop – February 14, 2014 (#1423) | 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: