Main() and command-line arguments (2023)

  • Article
  • 8 minutes to read

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 StartupObject compiler option to specify which Main method to use as the entry point. For more information, see StartupObject (C# Compiler Options).

class TestClass{ static void Main(string[] args) { // Display the number of command line arguments. Console.WriteLine(args.Length); }}

Starting in C# 9, you can omit the Main method, and write C# statements as if they were in the Main method, as in the following example:

using System.Text;StringBuilder builder = new();builder.AppendLine("Hello");builder.AppendLine("World!");Console.WriteLine(builder.ToString());

For information about how to write application code with an implicit entry point method, see Top-level statements.

Overview

  • The Main method is the entry point of an executable program; it is where the program control starts and ends.
  • Main is declared inside a class or struct. Main must 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.
  • Main can either have a void, int, Task, or Task<int> return type.
  • If and only if Main returns a Task or Task<int>, the declaration of Main may include the async modifier. This specifically excludes an async void Main method.
  • The Main method can be declared with or without a string[] parameter that contains command-line arguments. When using Visual Studio to create Windows applications, you can add the parameter manually or else use the GetCommandLineArgs() method 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 in the args array, but it is the first element of the GetCommandLineArgs() method.

The following list shows valid Main 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() { }public static async Task<int> Main() { }public static async Task Main(string[] args) { }public static async Task<int> Main(string[] args) { }

The preceding examples all use the public accessor modifier. That's typical, but not required.

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.

Main() return values

You can return an int from the Main method by defining the method in one of the following ways:

(Video) What are command line arguments (argc and argv)?

Main method codeMain signature
No use of args or awaitstatic int Main()
Uses args, no use of awaitstatic int Main(string[] args)
No use of args, uses awaitstatic async Task<int> Main()
Uses args and awaitstatic async Task<int> Main(string[] args)

If the return value from Main is not used, returning void or Task allows for slightly simpler code.

Main method codeMain signature
No use of args or awaitstatic void Main()
Uses args, no use of awaitstatic void Main(string[] args)
No use of args, uses awaitstatic async Task Main()
Uses args and awaitstatic async Task Main(string[] args)

However, returning int or Task<int> enables the program to communicate status information to other programs or scripts that invoke the executable file.

The following example shows how the exit code for the process can be accessed.

This example uses .NET Core command-line tools. If you are unfamiliar with .NET Core command-line tools, you can learn about them in this get-started article.

Create a new application by running dotnet new console. Modify the Main method in Program.cs as follows:

// Save this program as MainReturnValTest.cs.class MainReturnValTest{ static int Main() { //... return 0; }}

When a program is executed in Windows, any value returned from the Main function is stored in an environment variable. This environment variable can be retrieved using ERRORLEVEL from a batch file, or $LastExitCode from PowerShell.

You can build the application using the dotnet CLI dotnet build command.

Next, create a PowerShell script to run the application and display the result. Paste the following code into a text file and save it as test.ps1 in the folder that contains the project. Run the PowerShell script by typing test.ps1 at the PowerShell prompt.

Because the code returns zero, the batch file will report success. However, if you change MainReturnValTest.cs to return a non-zero value and then recompile the program, subsequent execution of the PowerShell script will report failure.

dotnet runif ($LastExitCode -eq 0) { Write-Host "Execution succeeded"} else{ Write-Host "Execution Failed"}Write-Host "Return value = " $LastExitCode
Execution succeededReturn value = 0

Async Main return values

When you declare an async return value for Main, the compiler generates the boilerplate code for calling asynchronous methods in Main. If you don't specify the async keyword, you need to write that code yourself, as shown in the following example. The code in the example ensures that your program runs until the asynchronous operation is completed:

(Video) Getting Command-Line Arguments in C

public static void Main(){ AsyncConsoleWork().GetAwaiter().GetResult();}private static async Task<int> AsyncConsoleWork(){ // Main body here return 0;}

This boilerplate code can be replaced by:

static async Task<int> Main(string[] args){ return await AsyncConsoleWork();}

An advantage of declaring Main as async is that the compiler always generates the correct code.

When the application entry point returns a Task or Task<int>, the compiler generates a new entry point that calls the entry point method declared in the application code. Assuming that this entry point is called $GeneratedMain, the compiler generates the following code for these entry points:

  • static Task Main() results in the compiler emitting the equivalent of private static void $GeneratedMain() => Main().GetAwaiter().GetResult();
  • static Task Main(string[]) results in the compiler emitting the equivalent of private static void $GeneratedMain(string[] args) => Main(args).GetAwaiter().GetResult();
  • static Task<int> Main() results in the compiler emitting the equivalent of private static int $GeneratedMain() => Main().GetAwaiter().GetResult();
  • static Task<int> Main(string[]) results in the compiler emitting the equivalent of private static int $GeneratedMain(string[] args) => Main(args).GetAwaiter().GetResult();

Note

If the examples used async modifier on the Main method, the compiler would generate the same code.

Command-Line Arguments

You can send arguments to the Main method by defining the method in one of the following ways:

Main method codeMain signature
No return value, no use of awaitstatic void Main(string[] args)
Return value, no use of awaitstatic int Main(string[] args)
No return value, uses awaitstatic async Task Main(string[] args)
Return value, uses awaitstatic async Task<int> Main(string[] args)

If the arguments are not used, you can omit args from the method signature for slightly simpler code:

Main method codeMain signature
No return value, no use of awaitstatic void Main()
Return value, no use of awaitstatic int Main()
No return value, uses awaitstatic async Task Main()
Return value, uses awaitstatic async Task<int> Main()

Note

(Video) Command Line Arguments | C Programming Tutorial

You can also use Environment.CommandLine or Environment.GetCommandLineArgs to access the command-line arguments from any point in a console or Windows Forms application. To enable command-line arguments in the Main method signature in a Windows Forms application, you must manually modify the signature of Main. The code generated by the Windows Forms designer creates Main without an input parameter.

The parameter of the Main method is a String array that represents the command-line arguments. Usually you determine whether arguments exist by testing the Length property, for example:

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

Tip

The args array can't be null. So, it's safe to access the Length property without null checking.

You can also convert the string arguments to numeric types by using the Convert class or the Parse method. For example, the following statement converts the string to a long number by using the Parse method:

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

It is also possible to use the C# type long, which aliases Int64:

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

You can also use the Convert class method ToInt64 to do the same thing:

long num = Convert.ToInt64(s);

For more information, see Parse and Convert.

The following example shows how to use command-line arguments in a console application. The application takes one argument at run time, converts the argument to an integer, and calculates the factorial of the number. If no arguments are supplied, the application issues a message that explains the correct usage of the program.

(Video) Command Line Arguments - CS50 Shorts

To compile and run the application from a command prompt, follow these steps:

  1. Paste the following code into any text editor, and then save the file as a text file with the name Factorial.cs.

    public class Functions{ public static long Factorial(int n) { // Test for invalid input. if ((n < 0) || (n > 20)) { return -1; } // Calculate the factorial iteratively rather than recursively. long tempResult = 1; for (int i = 1; i <= n; i++) { tempResult *= i; } return tempResult; }}class MainClass{ static int Main(string[] args) { // Test if input arguments were supplied. if (args.Length == 0) { Console.WriteLine("Please enter a numeric argument."); Console.WriteLine("Usage: Factorial <num>"); return 1; } // Try to convert the input arguments to numbers. This will throw // an exception if the argument is not a number. // num = int.Parse(args[0]); int num; bool test = int.TryParse(args[0], out num); if (!test) { Console.WriteLine("Please 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("Input must be >= 0 and <= 20."); else Console.WriteLine($"The Factorial of {num} is {result}."); return 0; }}// If 3 is entered on command line, the// output reads: The factorial of 3 is 6.
  2. From the Start screen or Start menu, open a Visual Studio Developer Command Prompt window, and then navigate to the folder that contains the file that you created.

  3. Enter the following command to compile the application.

    dotnet build

    If your application has no compilation errors, an executable file that's named Factorial.exe is created.

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

    dotnet run -- 3

  5. The command produces this output: The factorial of 3 is 6.

Note

When running an application in Visual Studio, you can specify command-line arguments in the Debug Page, Project Designer.

(Video) Command Line Arguments in Java

C# language specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See also

  • System.Environment
  • How to display command line arguments

FAQs

How many arguments can be passed to main ()? ›

The main() function has two arguments that traditionally are called argc and argv and return a signed integer.

Which is the correct way of declaring main () when it receives command line arguments? ›

int main(argc, argv) int argc; char *argv; C.

Can we pass arguments in main () in C? ›

Yes, we can give arguments in the main() function. Command line arguments in C are specified after the name of the program in the system's command line, and these argument values are passed on to your program during program execution. The argc and argv are the two arguments that can pass to main function.

How to solve error in not enough input arguments in matlab? ›

Now we have one more way to avoid the not enough input argument problem. We use the command line option when we execute the function at that same time; we need to pass the input argument for that function. By using this method, we can easily avoid this problem.

How many maximum arguments main () function can take? ›

The maximum number of arguments (and corresponding parameters) is 253 for a single function. Arguments are separated by commas.

How does Main () hold arguments passed to it? ›

main receives the number of arguments and the arguments passed to it when you start the program, so you can access it. argc contains the number of arguments, argv contains pointers to the arguments. argv[argc] is always a NULL pointer. The arguments usually include the program name itself.

What is the argument of main () method? ›

Since the main method is the entry point of the Java program, whenever you execute one the JVM searches for the main method, which is public, static, with return type void, and a String array as an argument.

What is command line argument example? ›

Example of Command Line Argument in C

#include <stdio.h> int main(int argc, char *argv[]) { int i; printf("\nProgram name: %5", argv[0]); if (argc < 2) { printf("\n\nNo argument passed through command line!" ); } else { printf("\nArgument supplied: "); for (i = 1; i < argc; i++){ printf("%s\t", argv[i]); } } }

How do you write codes in command line arguments? ›

Let's see the example of command line arguments where we are passing one argument with file name.
  1. #include <stdio.h>
  2. void main(int argc, char *argv[] ) {
  3. printf("Program name is: %s\n", argv[0]);
  4. if(argc < 2){
  5. printf("No argument passed through command line.\n");
  6. }
  7. else{
  8. printf("First argument is: %s\n", argv[1]);

Should main () always return a value in C? ›

The return value of main() function shows how the program exited. The normal exit of program is represented by zero return value. If the code has errors, fault etc., it will be terminated by non-zero value. In C++ language, the main() function can be left without return value.

Is Main () valid in C? ›

No. It's non-standard. The standard prototype of main is int main() with the optional command line arguments argc and argv . The int returned by main() is a way for a program to return a value to the system that invokes it.

Can we override main method in C? ›

To overcome the main() function, we can use them as class member. The main is not a restricted keyword like C in C++.

What does the error not enough input arguments mean in MATLAB? ›

This error means that you have not provided enough input arguments to the function. You need to provide more information to the function in order to run it properly. Follow this answer to receive notifications. answered Oct 11, 2022 at 14:03.

What is input () in MATLAB? ›

x = input( prompt ) displays the text in prompt and waits for the user to input a value and press the Return key. The user can enter expressions, like pi/4 or rand(3) , and can use variables in the workspace. If the user presses the Return key without entering anything, then input returns an empty matrix.

How do I show many arguments in MATLAB? ›

Input Arguments

To display more than one array, you can use concatenation or the sprintf or fprintf functions as shown in the example, Display Multiple Variables on Same Line.

How many main () function we can have? ›

We can't have more than one main() function in a project. Hint: Function can return only one value. If you want to return group of values then create a structure and return it.

Can a function have 3 arguments? ›

We pass arguments in a function, we can pass no arguments at all, single arguments or multiple arguments to a function and can call the function multiple times.

How do you fix too many arguments in a function? ›

Solution. So to fix the error “You've entered too many arguments for this function” you need to go through the content of the cell, character-by-character, to ensure that there are no syntax errors. In other words, you need to check whether all opened brackets are closed and all commas are properly in place.

What are the 3 main parts of an argument? ›

Toulmin identifies the three essential parts of any argument as the claim; the data (also called grounds or evidence), which support the claim; and the warrant. The warrant is the assumption on which the claim and the evidence depend.

How do you structure a main argument? ›

How to structure an argument
  1. Introduce the problem. Introduce the problem or issue at the center of your argument. ...
  2. Present your claim. After you provide your audience with sufficient context, you can present your claim or thesis statement. ...
  3. Support your claim. ...
  4. Acknowledge the opposing side of the argument. ...
  5. Restate your claim.
Jun 22, 2021

What are the 4 types of arguments? ›

Different Types Of Arguments: Deductive And Inductive Arguments
  • Type 1: Deductive Arguments.
  • Type 2: Inductive Arguments.
  • Type 3: Toulmin Argument.
  • Type 4: Rogerian Argument.
Sep 21, 2020

Which type of arguments main () accepts? ›

8) The type of Arguments the MAIN method accepts is ___. Explanation: Yes. The main method accepts String array data.

What is main () method? ›

The main() is the starting point for JVM to start execution of a Java program. Without the main() method, JVM will not execute the program. The syntax of the main() method is: public: It is an access specifier.

What is the function of main () method? ›

The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program.

What is the maximum number of arguments that can be passed in? ›

Explanation: No, C can accept upto 127 maximum number of arguments in a function.

How do you determine the number of passing arguments? ›

You can get the number of arguments from the special parameter $# . Value of 0 means "no arguments". $# is read-only. When used in conjunction with shift for argument processing, the special parameter $# is decremented each time Bash Builtin shift is executed.

What is the maximum number of arguments that you can pass to a script? ›

There is no limit on passed arguments, but that isn't the issue. You need to remember that the Java call to Runtime.

Is it possible to pass multiple arguments to a function? ›

Some functions are designed to return values, while others are designed for other purposes. We pass arguments in a function, we can pass no arguments at all, single arguments or multiple arguments to a function and can call the function multiple times.

Videos

1. Command-line Arguments - C++ Tutorial (Part 11)
(Steve's teacher)
2. Command Line Arguments In C: C Tutorial In Hindi #68
(CodeWithHarry)
3. Command line arguments in C++ | C++ Tutorial for Beginners
(ScoreShala)
4. Advanced Command Line Arguments
(programmingforthewin)
5. 6.C Programming - Command Line Arguments (int argc, char **argv)
(coding right)
6. Command Line Arguments in C | C Language Tutorial
(Naresh i Technologies)
Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated: 03/04/2023

Views: 5793

Rating: 4.9 / 5 (79 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.