This question already has an answer here:
In C# I have the following object:
public class Item
{ }
public class Task<T>
{ }
public class TaskA<T> : Task<T>
{ }
public class TaskB<T> : Task<T>
{ }
I want to dynamically create TaskA or TaskB using C# reflection (Activator.CreateInstance). However I wouldn't know the type before hand, so I need to dynamically create TaskA based on string like "namespace.TaskA" or "namespace.TaskAB".
I know this question is resolved but, for the benefit of anyone else reading it; if you have all of the types involved as strings, you could do this as a one liner:
Whenever I've done this kind of thing, I've had an interface which I wanted subsequent code to utilise, so I've casted the created instance to an interface.
It seems to me the last line of your example code should simply be:
Or am I missing something?
Make sure you're doing this for a good reason, a simple function like the following would allow static typing and allows your IDE to do things like "Find References" and Refactor -> Rename.
Check out this article and this simple example. Quick translation of same to your classes ...
Per your edit: For that case, you can do this ...
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:
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 :
and call it with :
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.