Skip to content

Your first console app#

Let's create a calculator console application with Add & Subtract operations.

Your first step is to create a console application.

Begin by creating the commands:

public class Program
{
    // this is the entry point of your application
    static int Main(string[] args)
    {
        // AppRunner<T> where T is the class defining your commands
        // You can use Program or create commands in another class
        return new AppRunner<Program>().Run(args);
    }

    // Add command with two positional arguments
    public void Add(int x, int y) => Console.WriteLine(x + y);

    // Subtract command with two positional arguments
    public void Subtract(int x, int y) => Console.WriteLine(x - y);
}
snippet source | anchor

That's it. You now have an application with two commands. Let's see about how we can call it from command line.

Assuming our application's name is calculator.dll, let's run this app from command line using dotnet. First we'll check out the auto-generated help.

$ dotnet calculator.dll --help
Usage: dotnet calculator.dll [command]

Commands:

  Add
  Subtract

Use "dotnet calculator.dll [command] --help" for more information about a command.
snippet source | anchor

From the root we can see the available commands. Instead of --help we could have used -h or -?. We'll use -h to get help for the Add command.

$ dotnet calculator.dll Add -h
Usage: dotnet calculator.dll Add <x> <y>

Arguments:

  x  <NUMBER>

  y  <NUMBER>
snippet source | anchor

Let's try it out by adding two numbers

$ dotnet calculator.dll Add 40 20
60
snippet source | anchor

CommandDotNet will validate if the arguments can be converted to the correct type.

$ dotnet calculator.dll Add a 20
'a' is not a valid Number
snippet source | anchor

Note

Usage can be updated to support .exe or when run as a dotnet tool. See the UsageAppNameStyle & UsageAppName sections.