views:

651

answers:

3

In C# you can put a constraint on a generic method like:

public class A {

    public static void <T> Method (T a) where T : new() {
        //...do something...
    }

}

Is there also a way to put a constraint like "there exists a constructor with a float[,] parameter?" The following code doesn't compile well:

public class A {

    public static void <T> Method (T a) where T : new(float[,] u) {
        //...do something...
    }

}

Or is there a work-around for it

+1  A: 

No. At the moment the only constructor constraint you can specify is for a no-arg constructor.

Sean Reilly
+5  A: 

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));
JaredPar
+8  A: 

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 <T> Method (T a, Func<float[,], T> creator) {
        //...do something...
    }

}
Tim Robinson
beautiful solution :) -- at least for certain scenarios, worked great for mine
Bobby