F#: Use reflection to call a private or protected method

This isn’t anything ground breaking so if you are expecting it to be, tough luck. The world doesn’t revolve around you. It revolves around me.

Making the switch to F# has caused me to redo a lot of older framework stuff and using reflection to call methods is part of that stuff. I could sit here and go on about something and waste your time, but I’ll be nice this time.

open System
open System.Reflection
 module ReflectionUtility =
  //This is used to make sure the GetMethod method doesn't skip private or protected
  let public BindingFlagsToSeeAll =
    BindingFlags.Static |||
    BindingFlags.FlattenHierarchy |||
    BindingFlags.Instance |||
    BindingFlags.NonPublic |||

  type MethodReflection public() =
    //Get the method by the method name from the class type
    member private x.FindMethodInfo<'targetClass>(methodName:String, source:'targetClass) =
      (source.GetType()).GetMethod(methodName, BindingFlagsToSeeAll)

    //Call the find method and run the found method
    member public x.ExecuteMethod<'returnType, 'target>(source:'target, methodName:String, argTypes:Type[], args:Object[]) =
      let info = x.FindMethodInfo(methodName, source)
      info.Invoke(source, args) :?> 'returnType

As you can see, this is extremely easy and short to use. I would suggest adding in some sort of caching if you are using this for anything that needs performance as I’m pretty sure reflection is still somewhat expensive. Most likely if I were caching anything it would be the method info.

If you’re new to F#, or due to an unfortunate turn of events ended up here, you might be wondering what all that ‘word stuff is or how the hell FindMethodInfo is returned

Well the ‘ notation is simply the way F# defines generic types.  It may look odd compared to C# but one nice thing is you never have to worry that your generic constraint might mirror the name of a variable/parameter/field.

The FindMethodInfo does have a return.  F# assumes that the last line in the method is the return.  This is really nice feature that saves a little bit of time by not having to type Return.  The other nice thing about it is that F# will infer the method’s return type by the last line so you never have to type out the return type for a method:


  public string ReturnString()
    return "";

  member public x.ReturnString() =

And that’s one reason why all the cool kids use F#.