Skip to content

Default Commands#

As we saw in the previous examples, a class can define commands using methods.

In those examples, the commands defined as methods are always subcommands.

There may be a case where an application should not have a subcommand

Or a case where a subcommand should have a default behavior and contain subcommands, such as Git's stash command, where stash will stash changes and stash pop will pop them from the stash stack.

CommandDotNet supports this with the [DefaultCommand] attribute used to decorate the method to execute.

public class Program
{
    static int Main(string[] args)
    {
        return new AppRunner<Program>().Run(args);
    }

    [DefaultCommand]
    public void Execute(int x, int y) => Console.WriteLine(x + y);
}
snippet source | anchor

$ add.exe Add -h
Usage: add.exe <x> <y>

Arguments:

  x  <NUMBER>

  y  <NUMBER>
snippet source | anchor

$ add.exe 40 20
60
snippet source | anchor

Command per class pattern#

Many console frameworks are designed solely to support the pattern of defining a command with a class. With these frameworks, the command class will contain an Execute method.

CommandDotNet does not force this pattern but can support it. Just create a class and decorate a method with [DefaultCommand]

public class Program
{
    static int Main(string[] args)
    {
        return new AppRunner<Program>().Run(args);
    }

    [Subcommand]
    public Add Add { get; set; }

    [Subcommand]
    public Subtract Subtract { get; set; }
}

public class Add
{
    [DefaultCommand]
    public void Execute(int x, int y) => Console.WriteLine(x + y);
}

public class Subtract
{
    [DefaultCommand]
    public void Execute(int x, int y) => Console.WriteLine(x - y);
}
snippet source | anchor

$ 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