Demo2 - Simple Math

A little bit math - implementing multiple commands

The Main application is always the same. However, we wrap it into a try/catch because we expect exceptions!

try {
    CommandHostBuilder.Create(args).Start();
}
catch (Exception ex) {
    Console.WriteLine(ex.Message);
}

We want to implement two different math commands:

  1. The first one adds two parameters provided in a command.line and prints the result on the Console

  2. The second command subtracts b from a and prints the result on the Console

[Command("MATH.ADD", "Add two integer values.")]
public class AddCommand : CommandBase2<AdditionContext>
{
    public AddCommand(IServiceProvider serviceProvider) : base(serviceProvider) {}

    protected override void Execute()
    {
        int result = this.Context.Value1 + this.Context.Value2;
        Console.WriteLine($"{this.Context.Value1} + {this.Context.Value2} = {result}");
    }
}

[Command("MATH.SUB", "Subtract two integer values.")]
public class SubCommand : CommandBase2<AdditionContext>
{
    public SubCommand(IServiceProvider serviceProvider) : base(serviceProvider) {}

    protected override void Execute()
    {
        int result = Context.Value1 - Context.Value2;
        Console.WriteLine($"{Context.Value1} - {Context.Value2} = {result}");
    }
}

public class AdditionContext
{
    [OptionDescriptor(
        "Value1", new []{"a1", "a"},
        required:true, defaultValue:0, helpText : "The first addend or the minuend." )]
    public int Value1 { get; set; }
    
    [OptionDescriptor(
        "Value2", new []{"a2","b"},
        required:true, defaultValue:0, helpText : "The second addend or the subtrahend." )]
    public int Value2 { get; set; }
}
> Demo2App MATH ADD /a=5 /b=7
5 + 7 = 12

> Demo2App MATH SUB /a=5 /b=7
5 - 7 = -2

> Demo2App MATH ADD /a=5
Missing mandatory Option: 'Value2' (Parameter 'Value2')

Last updated