In a C# application, the args parameter in the Main method is used to pass command-line arguments to the application when it is run. The arguments are typically passed as an array of strings.
static void Main(string[] args)
{
// Access the command-line arguments via args[]
}
You can run the program with the following command:
dotnet run arg1 arg2 arg3
In the Main method, the args array will contain:
args[0] = "arg1"
args[1] = "arg2"
args[2] = "arg3"
Now, let’s look at how to set static parameters for these args and how you can pass them statically from outside the code.
You can set static arguments using Visual Studio Code’s tasks.json configuration, which is used to automate build, run, and debug tasks. In the tasks.json, you can define a static set of arguments to pass to the application when it is run. This way, you don’t have to manually provide arguments each time.
{
"version": "2.0.0",
"tasks": [
{
"label": "Run Test Cases",
"command": "dotnet",
"type": "process",
"args": [
"run",
"--project",
"${workspaceFolder}/testcases/testcases.csproj",
"--",
"arg1",
"arg2",
"arg3"
],
"group": "none",
"presentation": {
"reveal": "always"
},
"problemMatcher": "$msCompile"
}
]
}
Accessing the static arguments in the Main method
Once the static parameters are passed to the args array via tasks.json, you can access them inside the Main method of your C# program.
using System;
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("No arguments were passed.");
}
else
{
Console.WriteLine("Arguments passed:");
foreach (var arg in args)
{
Console.WriteLine(arg);
}
}
}
}