Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I call this method via string?

Question from a Reflection newbie. I have a method in a Windows Form:

private void handleOrderCode()
{
  //...do stuff
}

Which I am trying to call in the following manner:

Type t = this.GetType();
MethodInfo mi = t.GetMethod("handleOrderCode");
if (mi != null) mi.Invoke(this, null);

I have confirmed that "this" is not null. The space where the string "handleOrderCode" has been hardcoded is to be replaced with a string variable when this works. However, at present "mi" is always null when it evaluates in the if statement in the final line.

So what am I doing wrong?

like image 203
One Monkey Avatar asked Mar 17 '26 20:03

One Monkey


2 Answers

You need to specify binding flags:

using System.Reflection;

t.GetMethod("handleOrderCode", BindingFlags.Instance | BindingFlags.NonPublic)

Because overload without any flag means:

BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance

i.e. will not return any non-public (private, protected, etc) members.

like image 132
abatishchev Avatar answered Mar 19 '26 11:03

abatishchev


The parameterless overload of Type.GetMethod only looks for public methods:

Searches for the public method with the specified name.

You need to specify an appropriate BindingFlags value to another overload instead:

MethodInfo method = t.GetMethod("handleOrderCode",
                                BindingFlags.Instance | BindingFlags.NonPublic);

Note that you need to specify "instance" or "static" here (or both), not just "non-public". If you want to look for public methods as well, you have to include that too.

Another alternative is just to make your method public :)

(Additionally, I'd suggest renaming it to HandleOrderCode to be more conventional, idiomatic C#.)

like image 26
Jon Skeet Avatar answered Mar 19 '26 11:03

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!