Home  >  Article  >  Backend Development  >  C# Command Line Arguments

C# Command Line Arguments

王林
王林Original
2024-09-03 15:07:091138browse

In C#, the program’s execution starts from the main() method. The main () method does not accept arguments from any other method, but it accepts arguments passed to it from the user via command line, and these arguments are called command-line arguments. Following are some important points regarding command line arguments in C#:

  • The main () method accepts arguments passed by the user in an array of type strings.
  • It accepts arguments during the execution of the program.
  • Users can convert these arguments of type string to other types in C# using the Convert class or Parse() method.

Syntax with explanation

The syntax of the Main() method taking command-line arguments is as follows:

static void Main(string[] args)
{
//user code
}

In the above syntax, ‘static’ is the keyword that indicates that the Main() method can execute without any instance. ‘void’ is the return type. ‘Main’ indicates that this is our Main() method of the program, and ‘string[]’ is the type of arguments passed to the method. ‘args’ is the user-defined name given to the arguments.

How Does Command Line Argument Work in C#?

Command-line arguments are passed to the Main() method as an array of type strings so we can pass n number of parameters while running our program.

Example:

public static void Main(string[] args)
{
//user code
}

When we pass the parameters to the above Main() method, it will be beheld by the ‘args’ variable, an array of type string. Then, we can access the individual argument from this array using the index position.

Earlier, each element passed will be of type string which can be later changed to the required data type using the Convert class or the Parse() method provided by C# as shown in the below examples:

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

The above statement will convert the argument present at index number 0 to an equivalent ‘long’ value using Parse() method, and then it will be stored in the variable’ num,’ which is of type’ long.’

int num = Convert.ToInt32(args[1]);

This statement will convert the argument present at index number 1 to an equivalent 32-bit signed integer, and then it will be stored in the variable ‘num,’ which is of type ‘int.’

We can also check for the existence of the command line arguments, i.e., to check whether the arguments are passed to the Main() method or not using the ‘Length’ property as shown below:

if (args.Length > 0)
{
System.Console.WriteLine("Arguments passed");
}
else
{
System.Console.WriteLine("Arguments are not passed");
}

For a windows forms application, to enable command-line arguments in the Main() method, we need to modify the signature of the Main() method in the file ‘program.cs’. This is because the windows forms designer generates the code which contains the Main() method without an input parameter.

If you are working with C# in the visual studio, then there is a nice way to enter command-line arguments for a Main() method in the visual studio. Following are some steps for this:

  1. Right-click on your project containing the solution explorer’s main () method.
  2. Click on ‘Properties’
  3. On the Properties window, go to the ‘Debug’ tab
  4. In Debug, there will be a text box saying ‘Command line arguments.’

We can enter command-line arguments in this text box, each separated by a space. Please find below the screenshot of the same:

C# Command Line Arguments

Examples of C# Command Line Arguments

Different examples are mentioned below:

Example #1

For example, taking ten integer numbers as input from the user through command-line arguments and checking for odd and even among these numbers.

Code:

using System;
using System.IO;
using System.Collections.Generic;
namespace ConsoleApp4
{
class Program
{
public static void Main(string[] args)
{
List<int> evenArray = new List<int>();
List<int> oddArray = new List<int>();
try
{
//checking if any argument exists
if (args.Length == 0)
{
Console.WriteLine("Please enter numbers to check for odd even!");
return;
}
//accessing arguments using for loop
for (int i = 0; i < args.Length; i++)
{
//checking for odd and even
if ((Convert.ToInt32(args[i]) % 2) == 0)
{
evenArray.Add(Convert.ToInt32(args[i]));
}
else
{
oddArray.Add(Convert.ToInt32(args[i]));
}
}
//displaying all the numbers entered
Console.WriteLine("Numbers entered:");
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine(args[i]);
}
//displaying even numbers entered
Console.WriteLine("\nEven numbers: ");
for (int i = 0; i < evenArray.Count; i++)
{
Console.WriteLine(evenArray[i]);
}
//displaying odd numbers entered
Console.WriteLine("\nOdd numbers: ");
for (int i = 0; i < oddArray.Count; i++)
{
Console.WriteLine(oddArray[i]);
}
Console.ReadLine();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}

Output:

C# Command Line Arguments

The screenshot containing the command to run the above program with inputs entered and with the output received is as follows:

Example #2

For example, taking a number from the user through the command line and calculating its factorial.

Code:

using System;
using System.IO;
using System.Collections.Generic;
namespace ConsoleApp4
{
class Program
{
public static void Main(string[] args)
{
int number;
int factorial;
try
{
//checking if any argument exists
if (args.Length == 0)
{
Console.WriteLine("Please enter a number to calculate " +
"its factorial!");
return;
}
if(args.Length > 1)
{
Console.WriteLine("Please enter only one number.");
return;
}
Console.WriteLine("The number entered is: " + args[0]);
number = Convert.ToInt32(args[0]);
factorial = number;
//calculating factorial of number using 'for' loop
for(int i = number - 1; i >= 1; i--)
{
factorial = factorial * i;
}
Console.WriteLine("Factorial of {0} is {1}: ", args[0], factorial);
Console.ReadLine();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}

Output:

C# Command Line Arguments

The screenshot containing the command to run the above program with the number entered and with the output received is as follows:

Note: We have executed the above two programs using “Developer Command Prompt for VS 2019”. We can also execute these programs from the visual studio by providing command line arguments through the ‘Command line arguments’ textbox in the ‘Debug’ option of the visual studio.

Conclusion

Command line arguments are parameters passed from the user to the Main() method of the program using the command line. The user enters these arguments during the execution of the program. These arguments are received by the Main() method in an array of type strings.

The above is the detailed content of C# Command Line Arguments. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:C# CommandsNext article:C# Commands