ckv
ckv

Reputation: 10830

Creating an object using Reflection: Activator.CreateInstance or Inovking the constructor C#

Which is the better way to create an object using reflection?

Getting a reference of the constructor and invoking the constructor to create the object or

Using Activator.CreateInstance on the Type of the class.

Better in the sense are there any specific reasons why we would opt for one method over the other? If so in what cases.

I am just learning reflection and had this question.

Upvotes: 2

Views: 118

Answers (1)

Josh
Josh

Reputation: 44906

They do the same thing. It's just easier to use Activator.CreateInstance.

Creates an instance of the specified type using the constructor that best matches the specified parameters.

Actually, you may net some performance benefit from using Activator since it caches constructor instances internally. If you are creating many of these in a loop, there is a good chance the Activator code is simply more optimized than a naive hand rolled implementation.

Upvotes: 5

Related Questions