- Article
- 8 minutes to read
Öprincipal
The method is the entry point of a C# application. (Libraries and services do not require aprincipal
method as an entry point.) When the application starts, theprincipal
method is the first method called.
There can be only one entry point into a C# program. If you have more than one class that has oneprincipal
method, you must compile your program using thestart objectCompiler option to specify whichprincipal
Method to use as an entry point. For more information, seeStartupObject (C#-Compileroptionen).
class TestClass{ static void Main(string[] args) { // Displays the number of command line arguments. Console.WriteLine(args.Length); }}
As of C# 9 you can omit thisprincipal
method and write C# statements as if they were in theprincipal
method, as in the following example:
using System.Text;StringBuilder builder = new();builder.AppendLine("Hallo");builder.AppendLine("World!");Console.WriteLine(builder.ToString());
For information about writing application code with an implicit entry point method, seeTop-level declarations.
overview
- Ö
principal
Method is the entry point of an executable program; This is where program control begins and ends. principal
is declared inside a class or struct.principal
we should bestaticand it doesn't have to bepublicly. (In the previous example, it gets the default access fromPrivate.) The enclosing class or struct need not be static.principal
can have onefile
,int
,task
, orTask<int>
return type.- then and only if
principal
returns onetask
orTask<int>
, the explanation ofprincipal
may include theasynchronousModifier. Exceptions to this are in particular aasynchronous invalid principal
Method. - Ö
principal
Method can be declared with or without acorda[]
Parameter containing command line arguments. If you use Visual Studio to build Windows apps, you can add the parameter manually or use theGetCommandLineArgs()to get the command line arguments. Parameters are read as null-indexed command-line arguments. Unlike C and C++, the program name is not treated as the first command-line argument in theargument
array, but it's the first element of theGetCommandLineArgs()Method.
The following list shows validprincipal
Signatures:
public static void Main() { }public static int Main() { }public static void Main(string[] args) { }public static int Main(string[] args) { }public static async Task Main() { }öffentlich static async Task<int> Main() { }public static async Task Main(string[] args) { }public static async Task<int> Main(string[] args) { }
All previous examples use thepublicly
access modifier. This is typical but not required.
the adding ofasynchronous
etask
,Task<int>
Return types simplify program code when console applications need to be started andexpect
asynchronous operationsprincipal
.
Main() return values
You can return oneint
vonprincipal
Define the method in one of the following ways:
principal Methodencode | principal signature |
---|---|
no use ofargument orexpect | static int Main() |
Usosargument , without usingexpect | static int Main(string[] args) |
no use ofargument , United States of Americaexpect | static asynchronous task<int> Main() |
Usosargument eexpect | Static asynchronous task<int> Main(string[] args) |
If the return value ofprincipal
not used, going backfile
ortask
allows for slightly simpler code.
principal Methodencode | principal signature |
---|---|
no use ofargument orexpect | Static Void Main() |
Usosargument , without usingexpect | static void Main(string[] args) |
no use ofargument , United States of Americaexpect | Main() static asynchronous task |
Usosargument eexpect | Static asynchronous task Main(string[] args) |
However, go backint
orTask<int>
allows the program to pass status information to other programs or scripts that call the executable.
The following example shows how the process exit code can be accessed.
This example uses.NET Corecommand line tools. If you're not familiar with the .NET Core command-line tools, you can learn about them hereinitial article.
Create a new application by running itdotnet new console
. modify theprincipal
method oneprogram.csas follows:
// Salve este programa como MainReturnValTest.cs.class MainReturnValTest{ static int Main() { //... return 0; }}
When a program runs on Windows, it returns any value specified by theprincipal
The function is stored in an environment variable. This environment variable can be retrieved withERROR LEVEL
from a batch file$LastExitCode
Macht PowerShell.
You can build the application usingPontonet CLI dotnet-Construction
Command.
Then create a PowerShell script to run the application and see the result. Paste the following code into a text file and save it astests.ps1
in the folder that contains the project. Run the PowerShell script by typingtests.ps1
no prompt for PowerShell.
Because the code returns zero, the batch file reports success. However, if you modify MainReturnValTest.cs to return a non-zero value and then recompile the program, subsequent execution of the PowerShell script will result in an error.
dotnet runif ($LastExitCode -eq 0) { Write-Host "Execution successful"} else{ Write-Host "Execution failed"} Write-Host "Return value = " $LastExitCode
Execution successful return value = 0
Asynchronous core return values
If you declare aasynchronous
return value forprincipal
, the compiler generates boilerplate code to call asynchronous methods inprincipal
. If you don't specify themasynchronous
keyword, you need to write this code yourself as shown in the example below. The code in the example ensures that your program runs until the asynchronous operation completes:
public static void Main(){ AsyncConsoleWork().GetAwaiter().GetResult();}private static async Task<int> AsyncConsoleWork(){ // Corpo principal aqui return 0;}
This boilerplate code can be replaced with:
static async Task<int> Main(string[] args){ return await AsyncConsoleWork();}
An advantage of the declarationprincipal
Ifasynchronous
is that the compiler always generates the correct code.
If the application's entry point returns atask
orTask<int>
, the compiler generates a new entry point that calls the entry point method declared in the application code. Suppose this entry point is called$GeneratedMain
, the compiler generates the following code for these entry points:
Static Main() task
will cause the compiler to emit the equivalent ofprivate static void $GeneratedMain() => Main().GetAwaiter().GetResult();
Static task Main(string[]).
will cause the compiler to emit the equivalent ofprivate static void $GeneratedMain(string[] args) => Main(args).GetAwaiter().GetResult();
Static Task<int> Main()
will cause the compiler to emit the equivalent ofprivate static int $GeneratedMain() => Main().GetAwaiter().GetResult();
Static Task<int> Main(string[])
will cause the compiler to emit the equivalent ofprivate static int $GeneratedMain(string[] args) => Main(args).GetAwaiter().GetResult();
monitoring
If the examples are usedasynchronous
modifier notprincipal
method, the compiler generates the same code.
command line arguments
You can send arguments toprincipal
Define the method in one of the following ways:
principal Methodencode | principal signature |
---|---|
No return value, no use ofexpect | static void Main(string[] args) |
Return value, without useexpect | static int Main(string[] args) |
No return value, useexpect | Static asynchronous task Main(string[] args) |
return value, usedexpect | Static asynchronous task<int> Main(string[] args) |
If no arguments are used, you can omitargument
from the method signature to some simpler code:
principal Methodencode | principal signature |
---|---|
No return value, no use ofexpect | Static Void Main() |
Return value, without useexpect | static int Main() |
No return value, useexpect | Main() static asynchronous task |
return value, usedexpect | static asynchronous task<int> Main() |
monitoring
You can also useenvironment.command lineorEnvironment.GetCommandLineArgsto access command-line arguments from anywhere in a console or Windows Forms application. How to enable command line arguments inprincipal
Method Signature In a Windows Forms application, you must manually change the method signatureprincipal
. Code generated by the Windows Forms Designer createdprincipal
without input parameters.
The parameter ofprincipal
method is aCordaArray representing the command line arguments. Typically, you determine if arguments are present by testing themLong
property, for example:
if (args.Length == 0){ System.Console.WriteLine("Please enter a numeric argument."); return 1;}
Top
Öargument
Array cannot be null. Therefore, access is secureLong
Property without null verification.
You can also convert string arguments to numeric types usingConverterclass or theAnalyze
Method. For example, the following statement converts thecorda
for onebig
number with theAnalyzeMethod:
long num = Int64.Parse(args[0]);
You can also use the C# typebig
what pseudonymsInt64
:
long num = long.Parse(args[0]);
You can also use theConverter
class methodToInt64
do the same:
long num = Convert.ToInt64(s);
For more information, seeAnalyzeeConverter.
The following example shows how command line arguments are used in a console application. The application takes an argument at runtime, converts the argument to an integer, and calculates the factorial of the number. If no arguments are given, the application prints a message explaining the correct use of the program.
To build and run the application from a command prompt, follow these steps:
Paste the following code into any text editor and save the file as a text file namedFatorial.cs.
public class Functions{ public static long Factorial(int n) { // Check for invalid input. if ((n < 0) || (n > 20)) { return -1; } // Calculate the factorial iteratively instead of recursively. long temp result = 1; for (int i = 1; i <= n; i++) { tempResult *= i; } Return TempResult; }}class MainClass{ static int Main(string[] args) { // Checks if input arguments were provided. if (args.Length == 0) { Console.WriteLine("Enter a numeric argument."); Console.WriteLine("Usage: Factorial <num>"); return 1; } // Attempt to convert input arguments to numbers. This will throw // an exception if the argument isn't a number. // num = int.Parse(args[0]); int number; test bool = int.TryParse(args[0], out num); if (!test) { Console.WriteLine("Enter a numeric argument."); Console.WriteLine("Usage: Factorial <num>"); return 1; } // Calculate factorial. long result = Functions.Factorial(num); // Print result. if (result == -1) Console.WriteLine("The entry must be >= 0 and <= 20."); else Console.WriteLine($"The factorial of {num} is {result}."); returns 0; }}// If 3 is entered on the command line, the // output is: The factorial of 3 is 6.
VonBeginscreen orBeginopen a visual studioDeveloper Command Promptwindow and navigate to the folder that contains the file you created.
Enter the following command to compile the application.
dotnet-Construction
If your application has no compilation errors, an executable namedFactorial.exeIt will be created.
Enter the following command to calculate the factorial of 3:
dotnet version – 3
The command produces this output:
The factorial of 3 is 6.
monitoring
When running an application in Visual Studio, you can supply command-line arguments in theDebug Page, Project Designer.
C# language specification
For more information, seeC# language specification. The language specification is the definitive source for C# syntax and usage.
also see
- System.Environment
- How to show command line arguments