In C# the Main class has string[] args parameter.
What is that for and where does it get used?
In C# the Main class has string[] args parameter.
What is that for and where does it get used?
From the C# programming guide on MSDN:
The parameter of the Main method is a String array that represents the command-line arguments
So, if I had a program (MyApp.exe) like this:
class Program
{
static void Main(string[] args)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
}
}
That I started at the command line like this:
MyApp.exe Arg1 Arg2 Arg3
The Main method would be passed an array that contained three strings: "Arg1", "Arg2", "Arg3".
If you need to pass an argument that contains a space then wrap it in quotes. For example:
MyApp.exe "Arg 1" "Arg 2" "Arg 3"
Command line arguments commonly get used when you need to pass information to your application at runtime. For example if you were writing a program that copies a file from one location to another you would probably pass the two locations as command line arguments. For example:
Copy.exe C:\file1.txt C:\file2.txt
Further to everyone else's answer, you should note that the parameters are optional in C# if your application does not use command line arguments.
This code is perfectly valid:
internal static Program
{
private static void Main()
{
// Get on with it, without any arguments...
}
}
For passing in command line parameters. For example args[0] will give you the first command line parameter, if there is one.
The args parameter stores all command line arguments which are given by the user when you run the program.
If you run your program from the console like this:
program.exe there are 4 parameters
Your args parameter will contain the four strings: "there", "are", "4", and "parameters"
Here is an example of how to access the command line arguments from the args parameter: example
You must have seen some application that run from the commandline and let you to pass them arguments. If you write one such app in C#, the array args serves as the collection of the said arguments.
This how you process them:
static void Main(string[] args) {
foreach (string arg in args) {
//Do something with each argument
}
}
This is an array of the command line switches pass to the program. E.g. if you start the program with the command "myapp.exe -c -d" then string[] args[] will contain the strings "-c" and "-d".
It's an array of the parameters/arguments (hence args) that you send to the program. For example ping 172.16.0.1 -t -4
These arguments are passed to the program as an array of strings.
string[] args // Array of Strings containing arguments.