views:

424

answers:

2

I am trying to use reflector.InvokeMethod to invoke a function with an optional parameter. The function looks like this:

Private Function DoSomeStuff(ByVal blah1 as string, ByVal blah2 as string, Optional ByVal blah3 as string = "45") as boolean
'stuff
end function

and I'm Invoking it like this:

Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2, Param3)

This works fine, other than when I don't pass the third (optional) parameter, it dosn't hit the function.

Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2)

Is there a way I can use Reflector.invokeMethod to call this function without passing the optional parameter? or another way to achieve this?

A: 

I would overload the DoSomeStuff method rather than use an optional parameter...

Private Overloads Function DoSomeStuff(ByVal blah1 As String, ByVal blah2 As String) As Boolean
    Return DoSomeStuff(blah1, blah2, "45")
End Function

Private Overloads Function DoSomeStuff(ByVal blah1 As String, ByVal blah2 As String, ByVal blah3 As String) As Boolean
    'stuff
End Function
whatknott
+1  A: 

The Visual Basic compiler actually substitutes the optional parameter values into the calling code. So if your actual code was:

DoSomeStuff(blah1, blah2)

Visual Basic would have emitted IL code equivalent to:

DoSomeStuff(blah1, blah2, "45")

To know what that last parameter is, you'll need to get a reference to the parameter's object (I'm not sure what that is in Reflector - in .NET you'd get access to the MethodInfo and then to the ParameterInfo), then get its custom attributes, looking for an attribute marked with OptionalAttribute and DefaultParameterValueAttribute. Then, you'll need to call it with the third parameter, supplying the value from DefaultParameterValueAttribute.

Rob