Generic Type in constructor

You can’t make constructors generic, but you can use a generic static method instead:

public static Constructor CreateInstance<T>(int blah, IGenericType<T> instance)

and then do whatever you need to after the constructor, if required. Another alternative in some cases might be to introduce a non-generic interface which the generic interface extends.

EDIT: As per the comments…

If you want to save the argument into the newly created object, and you want to do so in a strongly typed way, then the type must be generic as well.

At that point the constructor problem goes away, but you may want to keep a static generic method anyway in a non-generic type: so you can take advantage of type inference:

public static class Foo
{
    public static Foo<T> CreateInstance<T>(IGenericType<T> instance)
    {
        return new Foo<T>(instance);
    }
}

public class Foo<T>
{
    public Foo(IGenericType<T> instance)
    {
        // Whatever
    }
}

...

IGenericType<string> x = new GenericType<string>();
Foo<string> noInference = new Foo<string>(x);
Foo<string> withInference = Foo.CreateInstance(x);

Leave a Comment