views:

402

answers:

1

I have a Generic Type Interface and want a constructor of an object to take in the Generic Interface.
Like:

public Constructor(int blah, IGenericType<T> instance)
{}

I want the code that creates this object to specify the IGenericType (use Inversion of Control). I have not seen a way for this to happen. Any suggestions to accomplish this?

I want someone to create the object like:

Constructor varname = new Constructor(1, new GenericType<int>());
+7  A: 

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

public 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(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);
Jon Skeet
I would like to save the IGenericType as a member var, to do that I guess I would have to make the whole class generic not just the method...?
CSharpAtl
Yes, if you need it to be strongly typed as a member variable, then you should make the whole type generic and then the constructor problem goes away.
Jon Skeet
would like to run my design idea by you to see if there is something fundamentally better to do. Dont think I can type it all in this comment. Can I post to your blog or email you?
CSharpAtl