tags:

views:

73

answers:

5

Hi, I'm writing a reflection tool that I'll use for invoking methods from various types, and I'm testing it on simple programs.

I'm curious as why it doesn't return my Main() method on standard Visual Studio generated Program class

class Program { static void Main(string[] args) { return ; }

When I load type Program, and call type.GetMethods(); it returns 4 methods inherited from Object : ToString, GetHashCode, GetType and Equals.

I'm guessing Main is a special method as it's program's entry point, but there should be a way to retrieve its MethodInfo. Is there a way to get it?

A: 

Please try using BindingFlags.Static when calling GetMethods.

dhh
It's not the static-ness which is the problem - it's the fact that it's non-public.
Jon Skeet
+6  A: 

Your Main method is private, so you need to include BindingFlags.NonPublic.

(BindingFlags.Static is included by default, but NonPublic isn't.)

So:

var methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic |
                              BindingFlags.Static | BindingFlags.Instance);

(I'm assuming you want the public and instance methods as well, of course.)

Although Main is identified as the entry point here, there's nothing else that's particularly special about it - you can find it in the same way as other methods, and invoke it too.

Jon Skeet
I never know `BindingFlags.Static is included by default`, OMG. Sometimes we know something, but never try it!
Danny Chen
@Danny: To be fair, the documentation doesn't specify exactly what binding flags are passed, which would have been helpful :(
Jon Skeet
+3  A: 

GetMethods() returns all the public methods of the current Type.

You have to use GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic)

More info on Type.GetMethods(BindingsFlags)

madgnome
+1  A: 

Main() is not public by default:

type.GetMethods(BindingFlags.Static | BindingFlags.NonPublic);
Dmitry Karpezo
+2  A: 

The problem is that Main() is private and static. Try this:

      MethodInfo[] methods = typeof(Program).GetMethods(BindingFlags.Public
                                                      | BindingFlags.NonPublic
                                                      | BindingFlags.Static
                                                      | BindingFlags.Instance
                                                      );
Andy