C# Command Line Args
Syntax
public static void Main(string[] args)
Example
using System;
public class CommandLine
{
public static void Main(string[] args)
{
Console.WriteLine($"There are {args.Length} arguments.");
foreach (string s in args)
{
Console.WriteLine(s);
}
}
}
Output
C:\> CommandLine a b c
There are 3 arguments.
a
b
c
Explanation
C# command line arguments are a way to pass information to a console application when it is launched. The Main
method of the application can take an array of strings as a parameter to receive the command line arguments. This array contains all the arguments passed to the application when it was launched. The first element of the args
array is the name of the program itself.
In the example code above, the Main
method takes an array of strings args
as a parameter. The Console.WriteLine
method is used to output the number of arguments passed to the program. A foreach
loop is used to iterate over each argument in the args
array and output each one to the console.
Use
Command line arguments are used when you want to pass information to a console application when it starts up. This can be useful when you want to specify options or parameters for the program to use. For example, you might create a program that performs different tasks depending on the command line arguments passed to it.
Important Points
- The
Main
method of a console application can take an array of strings as a parameter to receive command line arguments. - The first element of the
args
array is the name of the program itself. - Command line arguments are useful for passing information to a console application when it is launched.
- They can be used to specify options or parameters for the program to use.
Summary
C# command line arguments are a way to pass information to a console application when it is launched. The Main
method of the application can take an array of strings as a parameter to receive the command line arguments. This array contains all the arguments passed to the application when it was launched. Command line arguments are useful when you want to specify options or parameters for the program to use.