Is there a generic constructor with parameter constraint in C#?
As you've found, you can't do this.
As a workaround I normally supply a delegate that can create objects of type T
:
public class A {
public static void Method<T> (T a, Func<float[,], T> creator) {
//...do something...
}
}
There is no such construct. You can only specify an empty constructor constraint.
I work around this problem with lambda methods.
public static void Method<T>(Func<int,T> del) {
var t = del(42);
}
Use Case
Method(x => new Foo(x));
Using reflection to create a generic object, the type still needs the correct constructor declared or an exception will be thrown. You can pass in any argument as long as they match one of the constructors.
Used this way you cannot put a constraint on the constructor in the template. If the constructor is missing, an exception needs to be handled at run-time rather than getting an error at compile time.
// public static object CreateInstance(Type type, params object[] args);
// Example 1
T t = (T)Activator.CreateInstance(typeof(T));
// Example 2
T t = (T)Activator.CreateInstance(typeof(T), arg0, arg1, arg2, ...);
// Example 3
T t = (T)Activator.CreateInstance(typeof(T), (string)arg0, (int)arg1, (bool)arg2);