Invoking methods with optional parameters through reflection

Alxandr picture Alxandr · Mar 11, 2010 · Viewed 21.7k times · Source

I've run into another problem using C# 4.0 with optional parameters.

How do I invoke a function (or rather a constructor, I have the ConstructorInfo object) for which I know it doesn't require any parameters?

Here is the code I use now:

type.GetParameterlessConstructor()
    .Invoke(BindingFlags.OptionalParamBinding | 
            BindingFlags.InvokeMethod | 
            BindingFlags.CreateInstance, 
            null, 
            new object[0], 
            CultureInfo.InvariantCulture);

(I've just tried with different BindingFlags).

GetParameterlessConstructor is a custom extension method I wrote for Type.

Answer

Matt Varblow picture Matt Varblow · Mar 28, 2012

According to MSDN, to use the default parameter you should pass Type.Missing.

If your constructor has three optional arguments then instead of passing an empty object array you'd pass a three element object array where each element's value is Type.Missing, e.g.

type.GetParameterlessConstructor()
    .Invoke(BindingFlags.OptionalParamBinding | 
            BindingFlags.InvokeMethod | 
            BindingFlags.CreateInstance, 
            null, 
            new object[] { Type.Missing, Type.Missing, Type.Missing }, 
            CultureInfo.InvariantCulture);