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.

1
  • Also I've removed the visual studio tag. Please only include relevant tags. Commented Mar 9, 2017 at 21:25

2 Answers 2

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"));
Sign up to request clarification or add additional context in comments.

4 Comments

And if I want to open a form like : Class c = new Class(); c.Show(); ?
Your class will inherit from Form, so you can use Form c = (Form)Activator.CreateInstance( ... )
Like that : Form c = (Form)Activator.CreateInstance(Type.GetType("Human.Person"); ? I have a ArgumentNullException
My Bad, an error in my class name. Now it works thx
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;

2 Comments

You don't need to load it, just add the assembly name to the type name like this "Human.Person,something"
You are right. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.