views:

54

answers:

3

basically

I have

string s = "Foo"

I need to obtain

 Type t = IRepo<Foo>

but from string

+4  A: 
Type t = typeof (IRepo<>).MakeGenericType(Type.GetType(s));
Yuriy Faktorovich
+7  A: 

Something like this, using Type.MakeGenericType:

Type arg = Type.GetType(s);
Type definition = typeof(IRepo<>);
Type concrete = definition.MakeGenericType(arg);

Note that Type.GetType(string) comes with a few caveats:

  • You need to specify the type's full name, including namespace
  • If you want to get a type from an assembly other than mscorlib or the calling assembly, you have to include the assembly name
  • If you're including the assembly name and it's strongly typed, you need the full assembly name including version etc.
Jon Skeet
A few more points:If you know which assembly the type exists in, you can use Assembly.GetType, which should be able to resolve a fully qualified type-name without assembly information being attached to the type-string.If all you have is "Foo", then AppDomain.CurrentDomain.GetAssemblies().SelectMany (a => a.GetTypes()).Single(t => t.Name == "Foo") or similar may be your only choice, but this is brittle and risky.
Ani
+1  A: 

You can do the following:

var someTypeName = "Foo";
var someType = Type.GetType("Namespace.To." + someTypeName);
typeof(IRepo<>).MakeGenericType(someType);

You first need to get the Type of Foo, and then you can pass that into Type.MakeGenericType.

Charles