#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());
        }
    }

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

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 comment