1

To create an instance of a class we can do that :

Person p = new Person();

But, I want to pass the name of class dynamicaly with a string like that :

String name = "Human.Person"
name n = new name();

I know this is wrong but I saw that I can use reflection but I didn't understand how can I use it for my case.

David L
  • 32,885
  • 8
  • 62
  • 93
Med
  • 183
  • 8

2 Answers2

2

You can use Activator.CreateInstance for this scenario.

object person = Activator.CreateInstance(Type.GetType("Human.Person"));

or most commonly using a base class or interface:

IPerson person = (IPerson)Activator.CreateInstance(Type.GetType("Human.Person"));
EventHorizon
  • 2,916
  • 22
  • 30
1
  Type t = Type.GetType(name); 
  Human.Person p = Activator.CreateInstance(t) as Human.Person;

Updated: Thanks @Dag If Human.person is in another assembly

Type t = a.GetType(name, "assemblyName"); 
Human.Person p = Activator.CreateInstance(t) as Human.Person;
Liu
  • 970
  • 7
  • 19