Axarydax
Axarydax

Reputation: 16603

C# Type.GetMethods() doesn't return Main() method

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?

Upvotes: 1

Views: 3577

Answers (5)

Julien Hoarau
Julien Hoarau

Reputation: 49970

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)

Upvotes: 3

Andy
Andy

Reputation: 3743

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

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

Upvotes: 2

Dmitry Karpezo
Dmitry Karpezo

Reputation: 1058

Main() is not public by default:

type.GetMethods(BindingFlags.Static | BindingFlags.NonPublic);

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499770

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.

Upvotes: 8

dhh
dhh

Reputation: 4337

Please try using BindingFlags.Static when calling GetMethods.

Upvotes: -1

Related Questions