Main() and command line arguments (2023)

  • Article
  • 8 minutes to read

ÖprincipalThe method is the entry point of a C# application. (Libraries and services do not require aprincipalmethod as an entry point.) When the application starts, theprincipalmethod 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 oneprincipalmethod, you must compile your program using thestart objectCompiler option to specify whichprincipalMethod 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 thisprincipalmethod and write C# statements as if they were in theprincipalmethod, 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

  • ÖprincipalMethod is the entry point of an executable program; This is where program control begins and ends.
  • principalis declared inside a class or struct.principalwe 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.
  • principalcan have onefile,int,task, orTask<int>return type.
  • then and only ifprincipalreturns onetaskorTask<int>, the explanation ofprincipalmay include theasynchronousModifier. Exceptions to this are in particular aasynchronous invalid principalMethod.
  • ÖprincipalMethod 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 theargumentarray, but it's the first element of theGetCommandLineArgs()Method.

The following list shows validprincipalSignatures:

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 thepubliclyaccess modifier. This is typical but not required.

the adding ofasynchronousetask,Task<int>Return types simplify program code when console applications need to be started andexpectasynchronous operationsprincipal.

Main() return values

You can return oneintvonprincipalDefine the method in one of the following ways:

principalMethodencodeprincipalsignature
no use ofargumentorexpectstatic int Main()
Usosargument, without usingexpectstatic int Main(string[] args)
no use ofargument, United States of Americaexpectstatic asynchronous task<int> Main()
UsosargumenteexpectStatic asynchronous task<int> Main(string[] args)

If the return value ofprincipalnot used, going backfileortaskallows for slightly simpler code.

principalMethodencodeprincipalsignature
no use ofargumentorexpectStatic Void Main()
Usosargument, without usingexpectstatic void Main(string[] args)
no use ofargument, United States of AmericaexpectMain() static asynchronous task
UsosargumenteexpectStatic asynchronous task Main(string[] args)

However, go backintorTask<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 theprincipalmethod 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 theprincipalThe function is stored in an environment variable. This environment variable can be retrieved withERROR LEVELfrom a batch file$LastExitCodeMacht PowerShell.

You can build the application usingPontonet CLI dotnet-ConstructionCommand.

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.ps1in the folder that contains the project. Run the PowerShell script by typingtests.ps1no 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 aasynchronousreturn value forprincipal, the compiler generates boilerplate code to call asynchronous methods inprincipal. If you don't specify themasynchronouskeyword, 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 declarationprincipalIfasynchronousis that the compiler always generates the correct code.

If the application's entry point returns ataskorTask<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() taskwill 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 usedasynchronousmodifier notprincipalmethod, the compiler generates the same code.

command line arguments

You can send arguments toprincipalDefine the method in one of the following ways:

principalMethodencodeprincipalsignature
No return value, no use ofexpectstatic void Main(string[] args)
Return value, without useexpectstatic int Main(string[] args)
No return value, useexpectStatic asynchronous task Main(string[] args)
return value, usedexpectStatic asynchronous task<int> Main(string[] args)

If no arguments are used, you can omitargumentfrom the method signature to some simpler code:

principalMethodencodeprincipalsignature
No return value, no use ofexpectStatic Void Main()
Return value, without useexpectstatic int Main()
No return value, useexpectMain() static asynchronous task
return value, usedexpectstatic 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 inprincipalMethod Signature In a Windows Forms application, you must manually change the method signatureprincipal. Code generated by the Windows Forms Designer createdprincipalwithout input parameters.

The parameter ofprincipalmethod is aCordaArray representing the command line arguments. Typically, you determine if arguments are present by testing themLongproperty, for example:

if (args.Length == 0){ System.Console.WriteLine("Please enter a numeric argument."); return 1;}

Top

ÖargumentArray cannot be null. Therefore, access is secureLongProperty without null verification.

You can also convert string arguments to numeric types usingConverterclass or theAnalyzeMethod. For example, the following statement converts thecordafor onebignumber with theAnalyzeMethod:

long num = Int64.Parse(args[0]);

You can also use the C# typebigwhat pseudonymsInt64:

long num = long.Parse(args[0]);

You can also use theConverterclass methodToInt64do 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:

  1. 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.
  2. VonBeginscreen orBeginopen a visual studioDeveloper Command Promptwindow and navigate to the folder that contains the file you created.

  3. Enter the following command to compile the application.

    dotnet-Construction

    If your application has no compilation errors, an executable namedFactorial.exeIt will be created.

  4. Enter the following command to calculate the factorial of 3:

    dotnet version – 3

  5. 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
Top Articles
Latest Posts
Article information

Author: Zonia Mosciski DO

Last Updated: 02/16/2023

Views: 6111

Rating: 4 / 5 (51 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Zonia Mosciski DO

Birthday: 1996-05-16

Address: Suite 228 919 Deana Ford, Lake Meridithberg, NE 60017-4257

Phone: +2613987384138

Job: Chief Retail Officer

Hobby: Tai chi, Dowsing, Poi, Letterboxing, Watching movies, Video gaming, Singing

Introduction: My name is Zonia Mosciski DO, I am a enchanting, joyous, lovely, successful, hilarious, tender, outstanding person who loves writing and wants to share my knowledge and understanding with you.