Pages

Saturday, January 29, 2011

Main entry point of a C# program

Like any other computer program, a program written in C# should have a default entry point. his entry point is where your code start executing.  Similar to many high level programming languages C# entry point is the “Main” method. (Libraries and services do not require a Main method as an entry point.) Main is also a member of a C# class or struct. This post is going to explain about few tricky points about usual C# main method and program execution.


Different ways of declaring “Main” method

There are four different syntax which we can use to declare main method.




Main must be static and should be declared as ‘private’ (even though access modifier is not mandatory). It should not be public. (In the earlier example, it receives the default access of private). When we declare main method as ‘int’ operating system waits for a return value. If the return value is 0, program execute without any error. But if it returns any other value than 0 it denotes the executions was a failure.

That return point value is cached internally for inter process communication. It’s very useful if the program is a part of a system of application (rest of the system can determine the success of the task assigned to the program)


Multiple Entry Points in a code

Even though its not recommended, it is possible to have more than one entry point in the same code. Consider the following code sample. Imagine this is stored in test.cs


using system;

  namespace Application {
   class FirstPro {
     static void Main (){
      // main block
     }
   }

   class SecondPro {
     static void Main (){
      // main block
     }
   }
  }
This code has two entry points and both are valid. Therefore we have to manually specify the desired entry point to run the program. This can be done using the ‘main’ compiler option.

   csc /main:Application.FirstPro test.cs


Command Line Arguments

The Main method can be declared with or without a string[] parameter. But that parameter contains command-line arguments which can be used to provide the program some values at the moment of execution. If you are using Visual Studio to create Windows Forms applications, (which is, the most obvious case) you can add the parameter manually or else can use the “Environment” class to obtain the command-line arguments. Parameters are read as zero-indexed command-line arguments. Unlike C and C++, the name of the program is not treated as the first command-line argument.

However, to enable command-line arguments in the Main method in a Windows Forms application, you must manually modify the signature of Main in program.cs. The code generated by the Windows Forms designer creates a Main without an input parameter.

2 comments:

  1. Thanks, only you wrote what happens when I have multiple entry points.

    ReplyDelete

Had to enable word verification due to number of spam comments received. Sorry for the inconvenience caused.