As you saw at the start of this chapter, C# programs start execution at a method named Main (). This must be a static method of a class (or struct), and must have a return type of either int or void.
Although it is common to specify the public modifier explicitly, because by definition the method must be called from outside the program, it doesn’t actually matter what accessibility level you assign to the entry-point method – it will run even if you mark the method as private.
Multlple Main() Methods
When a C# console or Windows application is compiled, by default-the compiler looks for exactly one Main () method ill any class matching the signature that was just described and makes that class method the entry point for the program. If there is more than one Main () method, the compiler will return an error message. For example, consider the following code called MainExample. cs:
This contains two classes, both of which have a Main () method. If you try to compile this code in the usual way, you will get the following errors:
However, you can explicitly tell the compiler which of these methods to use as the entry point for the program by using the /main switch, together with the full name (including namespace) of the class to which the Main () method belongs:
csc MainExample.cs /main:Wrox.ProCSharp.Basics.MathExample
Passing Arguments to Main()
The examples so far have shown only the Main () method ..without any parameters. However, when the program is invoked, you can get the CLR to pass any command-line arguments to the program by including a parameter. This parameter is a string array, traditionally called args (although C# will accept any name). The program can use this array to access any options passed through the command line . when the program is started.
The following sample, ArgsExample. cs, loops through the string array passed into the Main () method and writes the value of each option to the console window:
You can compile this as usual using the command line. When you run the compiled executable, you can pass in arguments after the name of the program, for example:
ArgsExample /a /b /e