Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is System.Activator.CreateInstance?

Tags:

.net

What is System.Activator.CreateInstance and when should I use it?

like image 570
Lev Avatar asked Feb 23 '12 08:02

Lev


1 Answers

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

public class MyClass
{
    public void SomeMethod()
    {

    }
}

and you wanted to create an instance of it. The standard way is to do this:

MyClass instance = new MyClass();

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:

// this could come from anywhere and it's known only at runtime
string someType = "MyClass"; 
object instance = Activator.CreateInstance(Type.GetType(someType));

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.

like image 120
Darin Dimitrov Avatar answered Sep 24 '22 01:09

Darin Dimitrov