Export (0) Print
Expand All
10 out of 12 rated this helpful - Rate this topic

new Constraint (C# Reference)

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. Apply this constraint to a type parameter when your generic class creates new instances of the type, as shown in the following example:

class ItemFactory<T> where T : new()
{
    public T GetNewItem()
    {
        return new T();
    }
}

When you use the new() constraint with other constraints, it must be specified last:

using System;
public class ItemFactory<T>
    where T : IComparable, new()
{
}

For more information , see Constraints on Type Parameters (C# Programming Guide).

For more information, see the following sections in the C# Language Specification:

  • 19.1.4 Constraints

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.