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?

Riddick
  • 1,278
  • 4
  • 17
  • 24
  • 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) – Benjamin Gruenbaum Oct 21 '13 at 22:31
  • see this post http://stackoverflow.com/questions/5858591/c-sharp-static-types-cannot-be-used-as-type-arguments – Sorceri Oct 21 '13 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. – Riddick Oct 22 '13 at 06:58

1 Answers1

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().

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794