Sum Command

Allow an argument to be provided many times

Sometimes it is helpful for an argument (a Context property) to be specified multiple times. We demonstrate this by implementing the Math SUM command that builds the total of any number of /Value arguments:

> MATH SUM /v=2 /Value=10 /VALUE=15 /v=3 /v=5,6,7 /v=1;2;3
10 values specified:
2+10+15+3+5+6+7+1+2+3 = 54

The magic is the AllowMultiple tag on the OptionDescriptor. It references a List that takes the arguments of the same tag. By specifying AllowMultipleSplit characters you can even specify multiple arguemnts in a row.

Note: The properties that AllowMultiple must be of type string, while the List property is of type .

public class SumContext
{   
    [OptionDescriptor("Value", "v", 
                      helpText:"Specify any number of value to built a total sum.",
                      AllowMultiple = nameof(Values),
                      AllowMultipleSplit = ";,")]
    public string Value { get; set; }
    
    public List<string> Values { get; set; } = new ();
}


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

    protected override void Execute()
    {
        Console.WriteLine($"{this.Context.Values.Count} values specified:");

        int total = 0;
        foreach (string sValue in this.Context.Values)
        {
            if( int.TryParse(sValue, out int value)) total += value;
        }
        
        Console.WriteLine($"{string.Join("+", this.Context.Values)} = {total}");
    }
}

Last updated