C# .NET – Generic Methods and Type Parameters in new() Constructor Constraint

.netc++genericstype-constraints

Is there a way to create a Generic Method that uses the new() constraint to require classes with constructor attributes of specific types?

For Example:

I have the following code:

public T MyGenericMethod<T>(MyClass c) where T : class
{
    if (typeof(T).GetConstructor(new Type[] { typeof(MyClass) }) == null)
    {
        throw new ArgumentException("Invalid class supplied");
    }
    // ...
}

Is it possible to have something like this instead?

public T MyGenericMethod<T>(MyClass c) where T : new(MyClass)
{
    // ...
}

EDIT: There's a suggestion regarding this. Please vote so we can have this feature in C#!

EDIT 2: The site has been taken down. Now the suggestion is on Github. Follow up there!

Best Answer

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));
Related Question