views:

177

answers:

1

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 and I know it doesn't require any parameters, but I still can't invoke it.

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 ExtensionMethod I wrote for Type.

+2  A: 

Optional parameters are denoted by an ordinary attribute and are handled by the compiler.
They have no effect (other than a metadata flag) on the IL, and are not directly supported by reflection (except for the IsOptional and DefaultValue properties).

If you want to use optional parameters with reflection, you'll need to manually pass their default values.

SLaks
Thank you. I came up with a solution that does exactly that. It doesn't look all that pretty, but it works. And also, IsOptional isn't the only property, DefaultValue also exists, so I just build an array out of all the DefaultValues.
Alxandr