Lev
Lev

Reputation: 3924

What is System.Activator.CreateInstance?

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

Upvotes: 9

Views: 5528

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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.

Upvotes: 21

Related Questions