dynamic generic creation using Type.GetType(string)?

J

jon

I'm trying to write a block of code that can create an instance of a
generic object, with the Type coming in as a dynamic string. It isn't
working yet. Any advice how I can dynamically create the appropriate
object to pass into the generic's constructing <T,U>?


-------------------------------
// fully qualified types as string
string type1Str = "ns1.ns2.control1, software.lib1";
string type2Str = "ns1.ns2.control2, software.lib1";

// create type objects
Type type1Type = Type.GetType(type1Str);
Type type2Type = Type.GetType(type2Str);

// try to create generic object passing in dynamic types
// this next line doesn't compile because of "type1Type" not being
appropriate here
GenericObj<type1Type, type2Type> genericObj = new
GenericObj<type1Type, type2Type>();

public class GenericObj<T,U> {
......
}
 
M

Marc Gravell

Something like:

Type final = typeof(GenericObj<,>).MakeGenericType(type1Type,
type2Type);
object obj = Activator.CreateInstance(final);

Marc
 
J

Jon Skeet [C# MVP]

jon said:
I'm trying to write a block of code that can create an instance of a
generic object, with the Type coming in as a dynamic string. It isn't
working yet. Any advice how I can dynamically create the appropriate
object to pass into the generic's constructing <T,U>?

You have to use reflection:

Type open = typeof(GenericObj<,>);
Type constructed = open.MakeGeneric(new Type[]{type1Type, type2Type});
object instance = Activator.CreateInstance(constructed);
....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top