What is System.Activator.CreateInstance and when should I use it?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It allows you to create an instance of an object whose type is known only at runtime. So let’s suppose that you have some class
and you wanted to create an instance of it. The standard way is to do this:
but as you can see this means that the type must be known at compile time. What if you wanted to have your user input the name of the class in some textbox. In this case you could use Activator.CreateInstance:
The drawback is that since the actual type is not known at compile time you will have to use reflection in order to manipulate the instances created with Activator.CreateInstance.