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...
return new T();
}
}
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...
return new T(new float[0,0]);
}
}
A workaround is also useful?
Method
in both examples to return an instance ofT
that is constructed inside each method body. By passing inT a
it's not clear that the desire is to be able to create an instance ofT
. – Andesstatic T Method<T>(float[,] a) => new T(a);
I know I'm using more recent C# syntax than when you asked the question 14 years ago!! – Andes