Home > Enterprise >  Getting MethodInfo at compile time for a non-static method
Getting MethodInfo at compile time for a non-static method

Time:09-22

I'm working on a program that calculates expressions at runtime based on a set of inputs, then executes those remotely. This requires creating expressions dynamically that call different helper functions.

For static helper functions, compile-time safety can be guaranteed by using the following to get a MethodInfo instance:

var myMethodInfo = ((Func<int, int>) Helpers.MyStaticHelper.DoSomethingUseful).Method

Using this, if Helpers.MyStaticHelper.DoSomethingUseful were to change it's name or signature, this would result in a compile-time error. However, it only appears to work for static methods. Using a similar approach for non-static gives a CS0120 An object reference is required for the nonstatic field, method, or property 'Helpers.MyDynamicHelper.DoSomethingElse(int, int)'.

A workaround is possible by using something like this:

var myMethodInfo = typeof(Helpers.MyDynamicHelper).GetMethod("DoSomethingElse")

However this risks a runtime exception if DoSomethingElse is altered. I'm aware it's not possible to invoke the method without an instance, but these instances are needed for collecting and caching prerequisite data, so any instance created before executing the expression would be incorrect.

Is it possible to get a compile-time safe MethodInfo for the method without an instance?

CodePudding user response:

You can use nameof to so ensure the method name is accurate:

var myMethodInfo = typeof(Helpers.MyDynamicHelper)
    .GetMethod(nameof(Helpers.MyDynamicHelper.DoSomethingElse));
  • Related