C# generic methods, type parameters in new() constructor constraint

Not really; C# only supports no-args constructor constraints.

The workaround I use for generic arg constructors is to specify the constructor as a delegate:

public T MyGenericMethod<T>(MyClass c, Func<MyClass, T> ctor) {
    // ...
    T newTObj = ctor(c);
    // ...

then when calling:

MyClass c = new MyClass();
MyGenericMethod<OtherClass>(c, co => new OtherClass(co));

Leave a Comment