A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/new-constraint below:

new constraint - C# reference

new constraint (C# Reference)

In this article

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

Apply the new constraint to a type parameter when a 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.

You can also use the new keyword to create an instance of a type or as a member declaration modifier.

C# language specification

For more information, see the Type parameter constraints section of the C# language specification.

See also

Collaborate with us on GitHub

The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.

Additional resources

In this article

Was this page helpful?


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4