2

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?

2
  • @NimsDotNet: Unless you call an instance method non-virtually in IL. It can be done :) Commented Apr 18, 2011 at 11:22
  • yeah, one of my Google searches on this before asking highlighted that there are some circumstances in which, weirdly, it can be, so I thought I'd double check. Belt and braces and all that. Commented Apr 18, 2011 at 11:37

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

you'd think that one of the many tuts on this that I Googled might mention that... but no. Thanks.
5

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#.)

Comments

4

try:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.