3

I have the following static class

public static class MyFoo<T> where T : class
{
    public static IBar<T> Begin()
    {
        return new Bar<T>();
    }
}

Elsewhere, I have a variable of System.Type, which I need to pass in as the Generic Type argument, ideally:

public void MyFunction(Type type)
{
     MyFoo<type>.Begin();
}

I know its possible through reflection to return an instance of MyFoo (If i make it non static) but this would not be ideal. Is there anyway to pass type as a Generic Type argument to the MyFoo static class?

3
  • 1
    First of all if you make it non-static you don't need reflection, you can enforce a parameterless constructor with a generic constraint on T. Second, what problem are you trying to solve here? Why isn't T a parameter of MyFunction (it can be inferred for you) Commented Oct 21, 2013 at 22:31
  • see this post stackoverflow.com/questions/5858591/… Commented Oct 21, 2013 at 22:31
  • Thanks for getting back to me. @BenjaminGruenbaum unfortunately I can't divulge too much but it would of been in my best interests if this was possible, to save myself a lot of time form something i've inherited. I shall un-static the situation! Thanks. Commented Oct 22, 2013 at 6:58

1 Answer 1

4

Can't do it. The value of the type variable in the second sample is only known at run time. The T type parameter in the first sample must be resolved at compile time.

Instead, look into Activator.CreateInstance().

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for getting back to me, I'll craft a workaround from a non static version :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.