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?
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.
Here is a workaround for this that I personally find quite effective. If you think of what a generic parameterized constructor constraint is, it's really a mapping between types and constructors with a particular signature. You can create your own such mapping by using a dictionary. Put these in a static "factory" class and you can create objects of varying type without having to worry about building a constructor lambda every time:
then in your generic method, for example:
I think this is the most clean solution that kind of puts a constraint on the way an object is constructed. It is not entirely compile time checked. When you have the agreement to make the actual constructor of the classes have the same signature like the IConstructor interface, it is kind of like having a constraint on the constructor. The
Constructor
method is hidden when working normally with the object, because of the explicit interface implementation.No. At the moment the only constructor constraint you can specify is for a no-arg constructor.
There is no such construct. You can only specify an empty constructor constraint.
I work around this problem with lambda methods.
Use Case
As you've found, you can't do this.
As a workaround I normally supply a delegate that can create objects of type
T
: