I have a class with a private static method with an optional parameter. How do I invoke it from another class via Reflection? There is a similar question, but it does not address static method or optional parameters.
public class Foo {
private static void Bar(string key = "") {
// do stuff
}
}
How do I invoke Foo.Bar("test") and Foo.Bar() (e.g. without passing the optional parameter)?
Optional parameter values in C# are compiled by injection those values at the callsite. I.e. even though your code is
The compiler actually generates a call like
When finding the method you need to treat the optional parameters as regular parameters.
If you know exactly what values you want to invoke the method with you can do:
If you only have some of the parameters and want to honor the values of the default ones you have to inspect the method’s
ParameterInfoobjects to see if the parameters are optional and what those values are. For example to print out the default values of those parameters you could use the following code: