Thursday 27 February 2014

Main() Method and its purpose?


The Main method is the entry point of a C# console application or windows application.When the application is started, the Main method is the first method that is invoked.

A main method is static because it is available to run when your program starts and as it is the entry point of the program it runs without creating an instance of the class.


  • Static  members are scoped to the class level (rather than the object level) and can thus be invoked without the need to first create a new class instance. In other words, static functions exist before a class is instantiated so static is applied to the main entry point (Main method).


  • By Default Main() is Private because the reason behind this other application can not invoke the entry point (Main() method) of another. However please note that we can declare the Main() method as public.
  • Return value of Main() method is void (indicates no return value) by default. We can change it to one of the following possible signatures. 
  • We can use int return value of the main method to check whether there is an error occurred in the main method. For ex if main method executes successfully then we will return 0 (this is the default value return by the main method even if it defined as void). If main method executes unsuccessfully then we will return -1.

The parameter of the Main method is a String array that represents the command-line arguments.

For Example:  if I had a program (MyApp.exe) like this:

class Program
{
  static void Main(string[] args)
  {
    foreach (var arg in args)
    {
      Console.WriteLine(arg);
    }
  }
}

That I started at the command line like this:

 MyApp.exe Arg1 Arg2 Arg3

The Main method would be passed an array that contained three strings: "Arg1", "Arg2", "Arg3".

If you need to pass an argument that contains a space then wrap it in quotes. For example:

MyApp.exe "Arg 1" "Arg 2" "Arg 3"

Command line arguments commonly get used when you need to pass information to your application at run time.
 
For example if you were writing a program that copies a file from one location to another you would probably pass the two locations as command line arguments.

 For example:
Copy.exe C:\file1.txt C:\file2.txt


If you have more than one class that has a Main method, then you must compile your program with the /main compiler option to specify which Main method to use as the entry point. (Refer Below Image)



To set this compiler option in the Visual Studio development environment
  • Open the project's Properties page.
  • Click the Application property page.
  • Modify the Start up object property.