Dela via


new Constraint (C# Reference)

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.

Example

Apply the new 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:

    public class ItemFactory2<T>
        where T : IComparable, new()
    {
    }

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

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See Also

Reference

C# Keywords

Operator Keywords (C# Reference)

Generics (C# Programming Guide)

System.Collections.Generic

Concepts

C# Programming Guide

Other Resources

C# Reference