views:

119

answers:

4

Basically what I need is to use the Type that i got using Type.GetType in a Generic Type,
is it possible, if yes how ? I need something like this:

Type t = Type.GetType("mynamespce.a.b.c");
var x = GenericClass<t>();

Duplicate

+2  A: 

It can be done: http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx (See section "Constructing an Instance of a Generic Type")

The following example creates a Dictionary<string,object>:

Type d1 = typeof(Dictionary<,>);
Type[] typeArgs = {typeof(string), typeof(object)};
Type constructed = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(constructed);
bitbonk
+1  A: 
Type t = Type.GetType("mynamespce.a.b.c");
Type gt = typeof(GenericClass<>).MakeGenericType(t);
var x = Activator.CreateInstance(gt);
Guillaume
+1  A: 

Yes, it is, but you will have to use further reflection. And you get the resulting object as a System.Object.

object obj = Activator.CreateInstance(typeof(GenericClass<>).MakeGenericType(Type.GetType("mynamespce.a.b.c")));
Maximilian Mayerl
+2  A: 

You can use Type.MakeGenericType and Activator.CreateInstance to make an instance of the generic type, e.g.

Type t = Type.GetType("mynamespce.a.b.c");
Type g = typeof(GenericClass<>).MakeGenericType(t);
object x = Activator.CreateInstance(g);

But it won't be strongly typed as the type of generic class in your code, if that's what you're looking for. That isn't possible as C# doesn't allow you to work with open generic types.

Greg Beech
too bad I wanted to use it for IoC.Resolve(g)
Omu
:) it actually worked, I did managed to do Ioc.Resolve(g), also got the method by reflection, and invoked it :)
Omu
You call your method like this: GenericClass<t>();In the method you cast to type of t: t x = Activator.CreateInstance(g) as t; (code is not tested)
Henrik Jepsen