0

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?

TheJediCowboy
  • 8,924
  • 28
  • 136
  • 208
  • 6
    Instantiate them with `new`. The fact that you're not doing this suggests that you need to create them dynamically, as you've already suggested. What is the problem you're having? ... Is it taking too long? Can you post the relevant code? Can you use a Factory pattern instead, or make use of Generics? – Robert Harvey Mar 21 '13 at 21:29
  • If you know there is a default constructor for the types, you can use the "new()" conatstraint and just create them with "new T()". Otherwise, keep/pass in a constructor delegate for each type. – Anders Forsgren Mar 21 '13 at 21:34
  • It sounds like the problem is at a higher level of your design architecture, such that you don't know as readily as you should what type of object you need. – Joel Coehoorn Mar 21 '13 at 21:37

1 Answers1

2

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.