Is there a generic constructor with parameter constraint in C#?
In C# you can put a constraint on a generic method like:
public class A {
public static void Method<T> (T a) where T : new() {
//...do something...
}
}
Where you specify that T
should have a constructor that requires no parameters. I'm wondering whether there is a way to add a constraint like "there exists a constructor with a float[,]
parameter?"
The following code doesn't compile:
public class A {
public static void Method<T> (T a) where T : new(float[,] u) {
//...do something...
}
}
A workaround is also useful?
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...
}
}
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);