generic generics

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi!
I want to do something like that :

class Test<T>{
}

string myVar = "System.String";
Type myType = Type.GetType( myVar );
Test<myType> delta = new Test<myType>();

Is it possible to do something like that ?
Thanks for your help
 
Joël said:
Hi!
I want to do something like that :

class Test<T>{
}

string myVar = "System.String";
Type myType = Type.GetType( myVar );
Test<myType> delta = new Test<myType>();

Is it possible to do something like that ?
Thanks for your help

I don't believe so - if my understanding of generics is correct, they are a
compile time feature. The value of myType cannot be determined until
runtime, so there would be no way to accomplish that.
 
Joël said:
Hi!
I want to do something like that :

class Test<T>{
}

string myVar = "System.String";
Type myType = Type.GetType( myVar );
Test<myType> delta = new Test<myType>();

Is it possible to do something like that ?
Thanks for your help

As written, no. You can create generic types via reflection using an
arbitrary type, but I'm not sure what it would buy you. What are you trying
to achieve with this code?

basic generic type construction code(untested, but should work):

string myVar = "System.String";
Type myType = Type.GetType( myVar );
Type testType = typeof(Test<>);
Type genericType = testType.MakeGenericType(new Type[] { myType });

object o = Activator.CreateInstance(genericType);

but you will only get as far as object or antoher base. You cannot treat the
reference as the given generic type due to compile time type checking.
 
Back
Top