Boolean parameters

May 10, 2011 at 3:42 AM

I'm trying to add a boolean parameter to my app... eg -v true|false (or --verbose true|false)

In the code when I define the option I use:


Option("v", "verbose", Required = false, HelpText = "Verbose mode. Defaults to false." )]
public bool Verbose = false ;

  everything looks fine but in practice things don't seem to happen how I expected....

if the user has "-v true" then... Verbose is set to true, but if they have "-v false" then Verbose still gets set to true. The only way it seems to set it to false is to leave the parameter off altogether. Entering "-v HelloMum" also doesn't fail... it sets Verbose to true

Ideally I'd like to see true | false acting as expected, and a spurious value generating an error ... unless I'm missing the point altogether and for a boolean value the mere existance of -v / --verbose will set the value to True and the lack sets it to the default... but how would that work if we wanted a default to be True and allow the user to override that with False (or confirm True explicitly)?


Jun 3, 2011 at 4:39 AM

Hit the same problem myself and I've hacked this into the source of LongOptionParser.cs, at line 79 in the 

it used to read

public sealed override ParserState Parse(IArgumentEnumerator argumentEnumerator, OptionMap map, object options) 
       var parts = argumentEnumerator.Current.Substring(2).Split(new char[] { '=' }, 2);


if (parts.Length == 2)

     		return ParserState.Failure;
if (parts.Length == 1)
     return ArgumentParser.BooleanToParserState(option.SetValue(true, options));
else if (parts.Length == 2)
     return ArgumentParser.BooleanToParserState(option.SetValue(bool.Parse(parts[1]), options));

return ParserState.Failure;

Test code looks like 

Jun 3, 2011 at 7:25 PM
Edited Jun 3, 2011 at 7:27 PM


I think the behavior you're seeing is expected. An option, e.g. -v, can be true (then it appears in the commandline) or false (then it doesn't appear there). This is based on the POSIX conventions for command line arguments, as described e.g. here:

As you can see there, this way to specify boolean options enables you to group options that do not require any arguments. e.g. if you have options -v, -w and -x, users can invoke your application by specifying something like -v -x or -v -w -x, but alternatively, they can simply write -vx or -vwx, respectively. If every boolean option required a "true" or "false" argument, this grouping wouldn't be possible.

As for your last question about how to set an option to true by default: Negate its name. If you want a short output by default and allow users to choose a more verbose one, offer a -v/--verbose option. If you want a verbose output by default and allow users to choose a more compact form, offer a -s/--short option or something like that.

Hope that helps :-)

Jun 30, 2011 at 11:41 AM

Hello everyone,

what fhaag says is 100% correct.

Thank you!

Good coding...