command-line-api icon indicating copy to clipboard operation
command-line-api copied to clipboard

Option of collection type with ArgumentArity.MaximumNumberOfValues = 1 parses incorrectly

Open elgonzo opened this issue 3 years ago • 1 comments

System.CommandLine version: 2.0.0-beta6.25320.118

Parsing fails in the (rather) unusual circumstance of a collection-type option (like Option<List<string>>) with an arity of ExactlyOne or ZeroOrOne.

var opt = new Option<List<string>>("--option1")
{
    Arity = ArgumentArity.ZeroOrOne    // or ArgumentArity.ExactlyOne
};

var rootCmd = new RootCommand
{
    opt
};

var parseResult = rootCmd.Parse("--option1 str1");
var val = parseResult.GetValue(opt);

Expected parse result

  • ParseResult: [ ConsoleApp1 [ --option1 <str1> ] ]
  • parseResult.GetValue(opt) returns a List<string> instance with a single "str1" item in it.

Actual result

  • ParseResult: [ ConsoleApp1 ![ --option1 <str1> ] ] (note the exclamation mark)
  • parseResult.GetValue(opt) throws InvalidOperationException

Exception message:

Cannot parse argument 'str1' for option '--option1' as expected type 'System.Collections.Generic.List`1[System.String]'.

Stack trace:

at System.CommandLine.Binding.ArgumentConverter.GetValueOrDefault[T](ArgumentConversionResult result)
at System.CommandLine.Parsing.OptionResult.GetValueOrDefault[T]()
at System.CommandLine.Parsing.SymbolResult.GetValue[T](Option`1 option)
at System.CommandLine.ParseResult.GetValue[T](Option`1 option)

elgonzo avatar Nov 16 '22 12:11 elgonzo

UPDATE: Tested the issue against 2.0.0-beta6.25320.118 and updated the report.

elgonzo avatar Jun 21 '25 19:06 elgonzo