10

I can use Type.InvokeMember to invoke a method via reflection, and it seems pretty robust, dealing with param array parameters for example. For some reason however it doesn't deal with optional parameters.

Is there any better built in approach for invoking a method (perhaps using the DLR) that does take into account optional parameters?

Avner Shahar-Kashtan
  • 14,492
  • 3
  • 37
  • 63
James Gaunt
  • 14,631
  • 2
  • 39
  • 57
  • You can call type.GetMethod(...) to get a MethodInfo instance. Then you can call methodInfo.Invoke(), for optional parameters, you can pass Type.Missing – huysentruitw Apr 02 '12 at 13:55
  • But this requires me to go to the effort of iterating over all possible instances of the method and working out if my parameters are appropriate given the optional parameters. Basically doing the binding manually which is what I'm doing at the moment. Just seems that Type.InvokeMember goes 90% of the way and then fails. Looking at the duplicate it appears I'm stuck doing it manually for now. – James Gaunt Apr 02 '12 at 13:57

1 Answers1

5

In following example, we are calling a function with two parameter that return nothing. Second param is optional.

MethodInfo mi = default(MethodInfo);

// Loading the assembly  
Assembly reflectionAssemby = Assembly.LoadFile(@"C:\RelectionDLL.dll");

// Get type of class from loaded assembly 
Type reflectionClassType = reflectionAssemby.GetType("ReflectionDLL.ReflectionClass");

// Create instance of the class 
object objReflection = Activator.CreateInstance(reflectionClassType);

mi = reflectionClassType.GetMethod("pub_Inst_NoReturn_Function");
mi.Invoke(objReflection, new object[] { value1, Type.Missing });
Peter Monks
  • 4,219
  • 2
  • 22
  • 38
Romil Kumar Jain
  • 20,239
  • 9
  • 63
  • 92
  • 1
    Thanks for the response. The problem with this is that I'd still need to dig into the metadata to determine that the optional parameter exists so that I can pass Type.Missing. I was hoping for a solution that basically replicated the binding capabilities of the C# compiler at runtime. – James Gaunt May 04 '12 at 17:30
  • @JamesGaunt Old post, but did you eventually find a way around this? – Barry D. Nov 11 '16 at 19:48
  • Wow yes very old... I did kind of find a way... but just by using the Roslyn compiler to compile the C# directly against the required dependencies at run-time. So not really solving the same problem. But there are probably ways to use the new compiler features to compile some sample code and then inspect the AST to see what it ended up binding too. – James Gaunt Nov 14 '16 at 13:11