Possible Duplicate:
Activator.CreateInstance – How to create instances of classes that have parameterized constructors
I was wondering how to create an object of a type determined at runtime without using the default constructor.
That is, I have BaseClass and various child classes.
Type type; //this variable will be one of the child classes
BaseClass base = Activator.CreateInstance(type);
This allows me to create a child class object with the default constructor, but I’d like to call a specific constructor. I know all of the child classes have a constructor taking certain parameters, so I have no worries of that constructor not existing. I found this question, but the best I can get there is a single string parameter. Is this doable?
Three options:
Type.GetConstructorand thenConstructorInfo.InvokeActivator.CreateInstancewhich takes arguments.Dictionary<Type, Func<string, string, YourBaseType>>or whatever’s appropriateThe third option requires you to change your factory code each time you add a new type, of course – but it’s only a single line.
Personally I like the first option, as it gives you the most control (rather than relying on
Activator.CreateInstancefinding the best matching constructor at execution time) – and if this is performance-sensitive code, you could build a dictionary of delegates at execution time by discovering the constructors, then using expression trees. (As far as I can tell, you can’t build a delegate from a constructor usingDelegate.CreateDelegate, which is somewhat annoying.)