Skip to content

where T new() (parameterless constructor)

Context: The new() constraint requires that the generic type has a public parameterless constructor. It allows creating instances of the type inside the generic class. This constraint must be the last if combined with others.

using System;
public class Factory<T> where T : new()
{
public T Create()
{
return new T(); // possible because of new()
}
}
public class Person
{
public string Name { get; set; }
public Person() => Name = "Unknown";
}
public class NoDefaultCtor
{
public NoDefaultCtor(string name) { }
}
class Program
{
static void Main()
{
var personFactory = new Factory<Person>();
Person p = personFactory.Create();
Console.WriteLine(p.Name); // Unknown
// This does not compile: NoDefaultCtor has no parameterless constructor
// var errorFactory = new Factory<NoDefaultCtor>();
}
}
Terminal window
dotnet run
Unknown
  • new() cannot be used with struct (structs always have an implicit default constructor, but the syntax is allowed).
  • If multiple constraints, new() must be last.

Activator.CreateInstance<T>() – Has the same parameterless constructor requirement.
See .NET docs on new().