Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does new() do in `where T: new()?`

Tags:

c#

.net

generics

What does the new() do in the code below?

public class A<T> where T : B, new()
like image 894
Joshscorp Avatar asked Jul 06 '09 04:07

Joshscorp


People also ask

What is new () constraint in C#?

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.

How to use Constraints in c#?

Beginning with C# 8.0, you can use the notnull constraint to specify that the type argument must be a non-nullable value type or non-nullable reference type. Unlike most other constraints, if a type argument violates the notnull constraint, the compiler generates a warning instead of an error.

What is generic type Constraints in c#?

C# allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.


2 Answers

This is a constraint on the generic parameter of your class, meaning that any type that is passed as the generic type must have a parameterless constructor.

So,

public class C : B
{
    public C() {}
}

would be a valid type. You could create a new instance of A<C>.

However,

public class D : B
{
   public D(int something) {}
}

would not satisfy the constraint, and you would not be allowed to create a new instance of A<D>. If you also added a parameterless constructor to D, then it would again be valid.

like image 93
womp Avatar answered Oct 07 '22 17:10

womp


The new() constraint means T has to have a public parameterless constructor. Any calls to T() get turned into calls to various overloads of Activator.CreateInstance(). A more flexible approach (say, if the constructors need arguments, or are internal rather than public) is to use a delegate:

public class A<T> where T : B
{
    public void Method(Func<T> ctor)
    {
        T obj = ctor();
        // ....
    }
}

// elsewhere...
public class C : B
{
    public C(object obj) {}  
}

public void DoStuff()
{
    A<C> a = new A<C>();
    object ctorParam = new object();
    a.Method(() => new C(ctorParam));
}
like image 20
thecoop Avatar answered Oct 07 '22 18:10

thecoop