Constructors

Let's say we want to add a class level field which is useful in both Addition and Subtraction. So now the class looks something like this-

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Calculator
{
    private readonly bool _printValues;

    public Calculator(bool printValues)
    {
        _printValues = printValues;
    }

    [ApplicationMetadata(Description = "Adds two numbers. duh!")]
    public void Add(int value1, int value2)
    {
        if (_printValues)
        {
            Console.WriteLine($"value1 : {value1}, value2: {value2}");
        }
        Console.WriteLine($"Answer:  {value1 + value2}");
    }

    public void Subtract(int value1, int value2)
    {
        if (_printValues)
        {
            Console.WriteLine($"value1 : {value1}, value2: {value2}");
        }
        Console.WriteLine($"Answer: {value1 - value2}");
    }
}

Let's see what the help command output looks like now

INPUT

1
dotnet example.dll --help

OUTPUT

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Usage: dotnet example.dll [options] [command]

Options:
  -h | -? | --help  Show help information
  --printValues     Flag

Commands:
  Add        Adds two numbers. duh!
  Subtract

Use "dotnet example.dll [command] --help" for more information about a command.

Let's try and invoke it

INPUT

1
dotnet example.dll --printValues Subtract 30 5

OUTPUT

1
2
value1 : 30, value2: 5
Answer: 25
Notes:

  • You can skip to pass any parameter. It will then fallback to the default value of parameter type

  • Any parameters in constructor are Options by default and you can't have Argument attribute in constructor parameters

  • Only one constructor is supported. If there are multiple, it will pick up first defined constructor

Inherited#

[Options] attribute has a property called Inherited. This is particularly useful when used with constructor options. When set to true, that option is can be passed to commands as well.


Last update: February 22, 2020