Note that Activator.CreateInstance<T>() or Activator.CreateInstance(Type) will only work with constructors without parameters. A constructor with optional arguments in this sense is not carefree.
Additional parameters (or arguments) are permitted by the C # compiler on the call site. However, when calling a constructor that uses reflection, the compiler is not involved in this way.
If you use the following code, you will receive a MissingMethodException message in which there is no constructor without parameters:
namespace ConsoleApplication1 { public class Foo { public Foo(int optional = 42) { } } class Program { static void Main(string[] args) { Activator.CreateInstance<Foo>();
In other words, the optional arguments are a compiler, not a CLR.
For more information on βcorner cases with extra arguments,β see this recent Eric Lippert blog series:
http://ericlippert.com/2011/05/09/optional-argument-corner-cases-part-one/
Having said that, you can somehow reproduce the desired behavior, using some reflection and manually creating the required parameters to call the constructor. The compiler will place some attributes inside the assembly that you can use for this purpose, I think.
Example:
public class Foo { public Foo([Optional, DefaultParameterValue(5)] int optional) { Console.WriteLine("Constructed"); } }
source share