Passing Arguments to a Console App
Learn about command-line arguments in C# console app, how to access and use them.
When we run a console app, we often want to change its behavior by passing arguments. For example, with the dotnet
command-line tool, we can pass the name of a new project template, as shown in the following commands:
dotnet new consoledotnet new mvc
We might have been wondering how to get any arguments that might be passed to a console app. In every version of .NET before version 6.0, the console app project template made it obvious, as shown in the following code:
using System;namespace Arguments{class Program{static void Main(string[] args){Console.WriteLine("Hello World!");}}}
Command-line arguments in top-level program
The string[]
args arguments are declared and passed in the Main
method of the Program
class. They’re an array
used to pass arguments into a console app. But in top-level programs, as used by the console app project template in .NET 6.0 and later, the Program
class and its Main
method are hidden, along with the declaration of the args array.
The trick is that we must know it ...