What does the new() do in the code below?
public class A<T> where T : B, new()
What does the new() do in the code below?
public class A<T> where T : B, new()
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.
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));
}