Search code examples
c#.netreflectioninvokedefault-value

Invoking methods with optional parameters through reflection


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.


Solution

  • 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);