Switches
Switch is a command line parameter that doesn’t have an explicit value, only “set/not set” states.
Switch may have:
- only one-char short name,
- only more-than-one-char long name,
- both short and long names.
Defining switches
Use a Switch()
method of parser or command to add a switch:
// Create a switch with short name only
var sw = parser.Switch('s');
// Create a switch with long name only
var sw = parser.Switch("switch");
// Create a switch with both short and long names
var sw = parser.Switch('s', "switch");
Configuration
Help text
Use either helpText
parameter of Switch()
method or a HelpText()
method of CliSwitch
to specify description for an autogenerated help:
var sw = parser.Switch('s', helpText: "Help text");
// or
sw.HelpText("Help text");
Hidden switch
Use either hidden
parameter of Switch()
method or a Hidden()
method of CliSwitch
to hide a switch from an autogenerated help:
var sw = parser.Switch('s', hidden: true);
// or
sw.Hidden();
Display order
Use DisplayOrder()
method of CliSwitch
to override switch display order in an autogenerated help:
// This example with generate help with the following ordering:
//
// OPTIONS
// z Switch Z
// a Switch A
//
// If you drop the DisplayOrder() call - you'll get this:
//
// OPTIONS
// a Switch A
// z Switch Z
var swA = parser.Switch('a');
var swZ = parser.Switch('z').DisplayOrder(-1000);
Consuming parsed values
You may access an IsSet
property to find out if a switch has been set.
CliSwitch<T>
is implicitly convertible to T
, so there is no need to access Value
property manually in most cases:
var sw = parser.Switch('s');
// ...
var isSet1 = sw.IsSet;
bool isSet2 = sw;
var isSet3 = (bool)sw;
var sw = parser.Switch('s');
// These two lines of code are identical
RunCommand(sw.IsSet);
RunCommand(sw);
// But these are not - x and y variables will have different types
var x = sw.Value;
var y = sw;
void RunCommand(bool sw)
{
Console.WriteLine($"Switch is \"{(sw ? "set" : "not set")}\"");
}
Repeatable switch
Usually switches can be specified only once. But there are cases when a switch might be set few times - e.g. a verbosity level switch:
# Default verbosility
my-program
# Extra verbosility
my-program -v
# Extra-extra verbosility
my-program -v -v
# or
my-program -vv
# Extra-extra-extra verbosility
my-program -v -v -v
# or
my-program -vvv
These switches are called repeatable switches.
Parser supports repeatable switches via RepeatableSwitch()
methods.
var sw = parser.RepeatableSwitch('s');
// ...
var isSet1 = sw.IsSet;
bool isSet2 = sw;
var isSet3 = (bool)sw;
var repeatCount1 = sw.RepeatCount;
int repeatCount2 = sw;
var repeatCount3 = (int)sw;
CliRepeatableSwitch<T>
has almost the same API as ordinary CliSwitch
.
Differencies are:
- It has an extra
RepeatCount
property indicating how many times a switch has been set. Zero value means a switch has not been set. - It’s implicitly convertible both to
bool
(providing value ofIsSet
) and tointeger
(providing value ofRepeatCount
).