tags:

views:

473

answers:

2

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

public class A<T> where T : B, new()
+27  A: 

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.

womp
Also if you have new() as generic constraint, you can actually instantiate T in your generic function, like so:T instance = new T();Without new() as constraint, there's no way to instantiate classes directly (you could still use a static factory, if you have a constraint to a specific class)
Steffen
Good point. You actually get a compile error if you try to do that, which is a nice way of reminding you to add the constraint.
womp
+1  A: 

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));
}
thecoop