Reputation: 10830
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
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