DotNet
DotNet

Reputation: 37

What is the difference between Activator.CreateInstance and a standard constructor?

What is the diffrenece between the two examples below? What is the purpose of Activator, why would I use it?

1.

string objTypeName = "Foo";
Foo foo = (Foo)Activator.CreateInstance(Type.GetType(objTypeName));

2.

Foo foo = new Foo()

I went through below the pages linked below, but didn't get a clear picture.

Here , here and here.

Upvotes: 1

Views: 861

Answers (3)

Jodrell
Jodrell

Reputation: 35716

If you know the type that you will instantiate at design time then there is no need to use Activator.CreateInstance. All Activator.CreateInstance does is call the public default constructor.

Activator.CreateInstance is one form of "Late Binding" that can be useful if you want to instantiate a Type that you do not know at design time. If you already know the type of the concrete class at design time then you definitely want to instantiate it using "Early Binding", its much faster and simpler, and obvious. i.e. call the appropriate constructor directly.

Upvotes: 2

hometoast
hometoast

Reputation: 11782

Activator.CreatInstance will call class Foo's default constructor.

The only difference is, if you know your type ahead of type, then creating it with new make a lot more sense (and readability)

Upvotes: 1

pascalhein
pascalhein

Reputation: 5846

With Activator.CreateInstance you can create objects even when cannot directly access the class it should belong to (e.g. Reflection), so you can for example create an object of the same type as another object:

var duplicate = Activator.CreateInstance(original.GetType());

This is not possible if you do not exactly know the class of your original object.

Upvotes: 2

Related Questions