developer747
developer747

Reputation: 15958

Pass in Generic Type to a method

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

}

Upvotes: 0

Views: 351

Answers (1)

SLaks
SLaks

Reputation: 888037

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

Upvotes: 5

Related Questions