-3

In a namespace I have an arbitrary number of classes fulfilling an interface IModel. Given the name of a class as a string, I want to instantiate that class and store the resulting object in a variable of type IModel.

As I have no experience in reflection, I did not figure out how to do it.

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142
  • 2
    ... or of [this](http://stackoverflow.com/questions/7398147/how-do-i-create-an-instance-from-a-string-that-provides-the-class-name?lq=1) or [this](http://stackoverflow.com/questions/7518383/how-do-i-create-an-object-from-a-string?lq=1) or [this](http://stackoverflow.com/questions/648160/how-do-i-create-an-instance-from-a-string-in-c?lq=1) or [this](http://stackoverflow.com/questions/493490/converting-a-string-to-a-class-name?lq=1) ... – O. R. Mapper May 14 '14 at 08:47
  • 1
    This question has been asked over and over. If a site suggests to check whether a question has already been asked before, **please do so**. – O. R. Mapper May 14 '14 at 08:48

3 Answers3

1

You could have a look at Activator.CreateInstance.

Paolo Tedesco
  • 55,237
  • 33
  • 144
  • 193
1

You don't need reflection here - use Activator

IModel model = (IModel)Activator.CreateInstance(Type.GetType(typeName));
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
1

There are many ways to do this. I do the following:

Type t = Type.GetType("<name of class>");
IModel m = (IModel)Activator.CreateInstance(t); // assuming constructor has no parameters
John Källén
  • 7,551
  • 31
  • 64