1

I know the type of object (let's say IAnimal) I need to instantiate, and the name (lets say Tiger). How do I write the code to instantiate Tiger, given that the variable that knows the object name is a string. I'm likely missing something simple here, but am currently stuck on this.

Update: I meant Class Tiger : IAnimal, changed above to reflect that.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
alchemical
  • 13,559
  • 23
  • 83
  • 110

3 Answers3

5

Using the Activator.CreateInstance method

example:

// the string name must be fully qualified for GetType to work
string objName = "TestCreateInstance.MyObject";
IProcess txObject = (IProcess)Activator.CreateInstance(Type.GetType(objName));

or

object o = Activator.CreateInstance("Assem1.dll", "Friendly.Greeting");

See also: Reflection Examples C#

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
1

Use reflection to instantiate an object of a class by its type name.

object o = Activator.CreateInstance(Type.GetType("Tiger"));

Note that you cannot instantiate interfaces (judging by your naming), as they are merely a contract that defines what a specific class should implement.

Wim
  • 11,998
  • 1
  • 34
  • 57
0

I am not sure I fully understand the question. However, assuming that ITiger is actually a concrete class and not an interface (as the I* would suggest).

You can use reflection to create and instance of a type from a string.

Something like:

ITiger myTiger = Activator.CreateInstance("ITiger") as ITiger;

http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx

Is that what you are asking?

VMAtm
  • 27,943
  • 17
  • 79
  • 125
Brad Cunningham
  • 6,402
  • 1
  • 32
  • 39