Reputation: 9232
I have a lot of pieces of code which currently use Activator.CreateInstance() to create objects based off the type. Is there a more optimized way of accomplishing this?
Upvotes: 0
Views: 283
Reputation: 184
I will assume that you are unable to use the new
keyword because you are creating an instance of an object via a generic factory.
Your options are limited as to how you can instantiate an object via reflection. Other than Activator.CreateInstance
and its derivatives, the only way I know of you can instantiate an object using a generic type definition is by declaring the new constraint. This allows you to call new T()
. The object you are instantiating must declare a parameterless constructor for this to work.
If performance is paramount, then I would recommend you avoid any reflectance or generic based patterns of object instantiation and create instances of the objects in question using the new keyword where possible.
Upvotes: 2