Saturday, March 24, 2007

Multiple Entry Points

A dot net program has a single point of entry (which is generally the Main function).
public static void Main(int args[])

A well-known fact:The execution of the program starts from here. If we look at the sig of the function we see that the Main function is publi. But ever wondered what happens if the sig is: private static void Main(int args[])?

The Main method is invoked from outside of the program. So it is, obviously, essential that the method be public. But would the program compile if it was private? The answer is: YES. It would compile. For some reason, not so obvious to me, the compiler/runtime doesn't see difference between a public and a private Main method. All it needs is a Main method.

So what if, in a program, we have two Main methods, either private or public or both? The compiler/runtime is confused. It doesn't know which is the actual point of entry. So, ambiguity! Hence, errors!

But what if for some reason you want to have two main methods? Can you make things work or is it the end of the road? It's definitely not the end. You can still make it work, with as many Main methods you want. Only condition being, the fully qualified name of the method (or the type containing it) should be different from each of the other Main methods.
namespace MainNamespace
{
class FirstMain
{
public static void Main(int args[]) {}
}

class SecondMain
{
public static void Main(int args[]) {}
}
}

To build this program use:
csc.exe Program.cs /main:MainNamespace.FirstMain

This will do the trick for you.
The next obvious question is how would we compile it using VS 2005? I would take this in my next post.

No comments: