mHelpMe mHelpMe - 4 months ago 31
C# Question

trying to use GetMethod to initialise MethodInfo variable

I am trying to call a function by passing a string which contains the function name.

Below is my code, neither of which work. The problem is that my MethodInfo variable mi is always null.

In debug I used the GetMethods method to see all the functions that are listed. The function I am trying to call is listed, I have double checked the spelling. What am I doing wrong?

object[] paraArray = new object[] { corpAct, secEvents };
MethodInfo mi = this.GetType().GetMethod(corpAct.DelegateName);
mi.Invoke(this, paraArray);

Second attempt

Type[] paraTypes = new Type[] { typeof(IHoldingLog), typeof(SecurityEvent) };
object[] paraArray = new object[] { corpAct, secEvents };
MethodInfo mi = this.GetType().GetMethod(corpAct.DelegateName, paraTypes);
mi.Invoke(this, paraArray);

The function it is trying to call,

void myFunction(IHoldingLog log, SecurityEvent sec)


I just tried using the line below but still getting mi as null

MethodInfo mi = this.GetType().GetMethod(corpAct.DelegateName, BindingFlags.NonPublic);


By default, GetMethod will only return public instance or static methods. So if you do not specify BindingFlags, by default it will fall back to BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public.

Use the following call variant to include also non-public methods.

this.GetType().GetMethod("myMethod", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)

If your method has overloads, then you can use the GetMethod overload which allows you to specify the parameter types to identify which overload you wish to target (as in your second example). If your method does not have overloads, then no need to specify the parameter types.