-1

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

Community
  • 1
  • 1
Omu
  • 69,856
  • 92
  • 277
  • 407

4 Answers4

3

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
  • 48,890
  • 37
  • 186
  • 278
2

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
  • 133,383
  • 43
  • 204
  • 250
  • too bad I wanted to use it for IoC.Resolve(g) – Omu Dec 01 '09 at 09:09
  • :) it actually worked, I did managed to do Ioc.Resolve(g), also got the method by reflection, and invoked it :) – Omu Dec 01 '09 at 09:55
  • You call your method like this: GenericClass(); In the method you cast to type of t: t x = Activator.CreateInstance(g) as t; (code is not tested) – Henrik Gering Dec 01 '09 at 10:20
1
Type t = Type.GetType("mynamespce.a.b.c");
Type gt = typeof(GenericClass<>).MakeGenericType(t);
var x = Activator.CreateInstance(gt);
Guillaume
  • 12,824
  • 3
  • 40
  • 48
1

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
  • 11,253
  • 2
  • 33
  • 40