Problem
If I use a nullable type for an Option<T> (which is useful for determining whether the option was specified at all), and an invalid value is provided to that Option on the command line, the application will crash with an InvalidOperationException. It does not crash if the Option type is not nullable.
I will freely admit that using a nullable type for an Option may not be the "correct" approach; it seemed like the most expedient way to identify whether an option was specified by the user.
Example for Reproducing
For example, invoking the following application with arguments "--test ouch" will crash:
using System.CommandLine;
using System.CommandLine.Builder;
using System.CommandLine.Parsing;
RootCommand rootCommand = new("example-app");
Option<bool?> testOption = new("--test");
rootCommand.AddOption(testOption);
rootCommand.SetHandler(rootHandler, testOption);
CommandLineBuilder builder = new(rootCommand);
return builder.Command.InvokeAsync(args).Result;
async Task<int> rootHandler(bool? test)
{
Console.WriteLine("In handler");
return 0;
}
Unhandled exception: System.InvalidOperationException: Cannot parse argument 'ouch' for option '--test' as expected type 'System.Boolean'.
at System.CommandLine.Binding.ArgumentConverter.GetValueOrDefault[T](ArgumentConversionResult result)
at System.CommandLine.Parsing.SymbolResult.GetValueForOption[T](Option`1 option)
...
But if I change it to Option<bool> instead of Option<bool?> (and the corresponding change to rootHandler), then there's no crash:
'ouch' was not matched. Did you mean one of the following?
-h
Unrecognized command or argument 'ouch'.
Description:
example-app
...
Proposed Solutions
- Support nullable types for Option so they are handled more like "regular" types from an end user standpoint.
- Block the use of nullable types for Option (provided there is a different/better way to determine whether an option was specified).
Problem
If I use a nullable type for an
Option<T>(which is useful for determining whether the option was specified at all), and an invalid value is provided to that Option on the command line, the application will crash with an InvalidOperationException. It does not crash if the Option type is not nullable.I will freely admit that using a nullable type for an Option may not be the "correct" approach; it seemed like the most expedient way to identify whether an option was specified by the user.
Example for Reproducing
For example, invoking the following application with arguments "--test ouch" will crash:
But if I change it to
Option<bool>instead ofOption<bool?>(and the corresponding change to rootHandler), then there's no crash:Proposed Solutions