| title | Main() and command-line arguments (C# Programming Guide) | |||||
|---|---|---|---|---|---|---|
| ms.date | 08/02/2017 | |||||
| ms.prod | .net | |||||
| ms.technology |
|
|||||
| ms.topic | article | |||||
| f1_keywords |
|
|||||
| helpviewer_keywords |
|
|||||
| ms.assetid | 73a17231-cf96-44ea-aa8a-54807c6fb1f4 | |||||
| caps.latest.revision | 30 | |||||
| author | BillWagner | |||||
| ms.author | wiwagn |
The Main method is the entry point of a C# application. (Libraries and services do not require a Main method as an entry point.) When the application is started, the Main method is the first method that is invoked.
There can only be one entry point in a C# program. If you have more than one class that has a Main method, you must compile your program with the /main compiler option to specify which Main method to use as the entry point. For more information, see /main (C# Compiler Options).
[!code-csharpcsProgGuideMain#17]
- The
Mainmethod is the entry point of an executable program; it is where the program control starts and ends. Mainis declared inside a class or struct.Mainmust be static and it need not be public. (In the earlier example, it receives the default access of private.) The enclosing class or struct is not required to be static.Maincan either have avoid,int, or, starting with C# 7.1,Task, orTask<int>return type.- If and only if
Mainreturns aTaskorTask<int>, the declaration ofMainmay include theasyncmodifier. Note that this specifically excludes anasync void Mainmethod. - The
Mainmethod can be declared with or without astring[]parameter that contains command-line arguments. When using [!INCLUDEvsprvs] to create Windows applications, you can add the parameter manually or else use the xref:System.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.
The addition of async and Task, Task<int> return types simplifies program code when console applications need to start and await asynchronous operations in Main.
[!INCLUDECSharplangspec]
Command-line Building With csc.exe C# Programming Guide Methods Inside a C# Program