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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
One Monkey
  • 713
  • 3
  • 9
  • 24
  • @NimsDotNet: Unless you call an instance method non-virtually in IL. It can be done :) – Jon Skeet Apr 18 '11 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. – One Monkey Apr 18 '11 at 11:37

3 Answers3

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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
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#.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

try:

Type t = this.GetType();
MethodInfo mi = t.GetMethod("handleOrderCode", 
   BindingFlags.NonPublic | BindingFlags.Instance);
if (mi != null) mi.Invoke(this, null);
Andrey
  • 59,039
  • 12
  • 119
  • 163