In C#, how to create an object given the name of its type? [duplicate]
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.
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#
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.
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?
精彩评论