Is there a generic constructor with parameter constraint in C#?

Willem Van Onsem picture Willem Van Onsem · Dec 5, 2009 · Viewed 81.7k times · Source

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?

Answer

Tim Robinson picture Tim Robinson · Dec 5, 2009

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...
    }

}