Command-Line Arguments
Part of the C# and .NET Basics section of Coddy's ASP.NET Core journey. Lesson 3 of 20.
Command-line programs take their input as words after the command. On your computer, dotnet run -- Ada Lovelace builds the program and passes it Ada and Lovelace. The -- separates the options for dotnet itself from the words meant for your program.
Top-level statements get those words in args, a string[] that is always there. args.Length says how many there are, and quotes keep words together: "Ada Lovelace" arrives as one string.
if (args.Length == 0)
{
Console.WriteLine("Who should I greet?");
}
else
{
Console.WriteLine($"Hello, {args[0]}! You passed {args.Length} words.");
}With Ada Lovelace it prints Hello, Ada! You passed 2 words.
Challenge
BeginnerThe tracker gets its first command: add, which takes a name and an amount.
- Put the three summary lines inside
if (args.Length == 0) { ... }. With no arguments the program prints the same three lines as before. - Add an
elseblock with aswitch (args[0]). - In
case "add":, printAdded, the name fromargs[1], a colon and the amount fromargs[2].dotnet run -- add Lunch 12.50prints:Added Lunch: 12.50 - In
default:, printUnknown command:and the command.dotnet run -- flyprintsUnknown command: fly.
Try it: the terminal beside the editor already reads dotnet run -- add Lunch 12.50, so press Run: Added Lunch: 12.50. Change the arguments after -- to fly and Run again: Unknown command: fly. Delete them all and Run once more to see the three summary lines.
Try it yourself
var count = 0;
var total = 0m;
Console.WriteLine("Expense Tracker");
Console.WriteLine($"{count} expenses");
Console.WriteLine($"Total: {total:F2}");