Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

new constraint (C# Reference)

  • 2024-03-30
Feedback

In this article

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

Apply thenew 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 thenew() constraint with other constraints, it must be specified last:

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

For more information, seeConstraints on Type Parameters.

You can also use thenew keyword tocreate an instance of a type or as amember declaration modifier.

C# language specification

For more information, see theType parameter constraints section of theC# 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, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo