How to dynamically create generic C# object using reflection? [duplicate]
Solution 1:
Check out this article and this simple example. Quick translation of same to your classes ...
var d1 = typeof(Task<>);
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
Per your edit: For that case, you can do this ...
var d1 = Type.GetType("GenericTest.TaskA`1"); // GenericTest was my namespace, add yours
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
To see where I came up with backtick1 for the name of the generic class, see this article.
Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:
Type type = typeof(IReadOnlyDictionary<,>);
Solution 2:
Indeed you would not be able to write the last line.
But you probably don't want to create the object, just for the sake or creating it. You probably want to call some method on your newly created instance.
You'll then need something like an interface :
public interface ITask
{
void Process(object o);
}
public class Task<T> : ITask
{
void ITask.Process(object o)
{
if(o is T) // Just to be sure, and maybe throw an exception
Process(o as T);
}
public void Process(T o) { }
}
and call it with :
Type d1 = Type.GetType("TaskA"); //or "TaskB"
Type[] typeArgs = { typeof(Item) };
Type makeme = d1.MakeGenericType(typeArgs);
ITask task = Activator.CreateInstance(makeme) as ITask;
// This can be Item, or any type derived from Item
task.Process(new Item());
In any case, you won't be statically cast to a type you don't know beforehand ("makeme" in this case). ITask allows you to get to your target type.
If this is not what you want, you'll probably need to be a bit more specific in what you are trying to achieve with this.
Solution 3:
It seems to me the last line of your example code should simply be:
Task<Item> itsMe = o as Task<Item>;
Or am I missing something?