Menu
CoddyTech

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 icon

Challenge

Beginner

The tracker gets its first command: add, which takes a name and an amount.

  1. Put the three summary lines inside if (args.Length == 0) { ... }. With no arguments the program prints the same three lines as before.
  2. Add an else block with a switch (args[0]).
  3. In case "add":, print Added, the name from args[1], a colon and the amount from args[2]. dotnet run -- add Lunch 12.50 prints:
    Added Lunch: 12.50
  4. In default:, print Unknown command: and the command. dotnet run -- fly prints Unknown 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}");

All lessons in C# and .NET Basics