0

Is this possible?

When a type gets passed in to a method, I want to instantiate the generic class myClass

public class myClass<T>
{

}

public void PassInType(Type myType)
{

myClass<myType> c=new myClass<myType>();
}

Update:

Okay since thats not possible, how do I do this

public myMethod(string myType)
{

myClass<myType> c=new myClass<myType>();

}
developer747
  • 15,419
  • 26
  • 93
  • 147

1 Answers1

5

No; that's fundamentally impossible.

The whole point of generics is that they create compile-time types.
You're trying to create a type which is unknown at compile time.

You can do it using reflection, though. (typeof(MyClass<>).MakeGenericType(myType))

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964