Skip to content

Option with Arity of ZeroOrOne or ZeroOrMore don't use DefaultValueFactory when option is given without value on the CLI #2257

Closed

Description

@elgonzo

System.CommandLine version: 2.0.0-beta6.25320.118

When setting up an option with an arity of ArgumentArity.ZeroOrOne or ArgumentArity.ZeroOrMore, it allows to provide the option without a value on the CLI. When no value is given for such an option, i would expect the DefaultValueFactory of the option to be called for providing the default value to fill in for the missing option value in the CLI invocation.

As an example, take this int option and command specification:

var opt = new Option<int>("-o")
{
    Arity = ArgumentArity.ZeroOrOne,
    DefaultValueFactory = _ =>
    {
        Console.WriteLine("DefaultValueFactory called");
        return 42;
    }
};

var rootCmd = new RootCommand
{
    opt
};

rootCmd.SetAction(
    parseResult =>
    {
        var optResult = parseResult.GetResult(opt)!;
        Console.WriteLine($"Value: {optResult.GetValueOrDefault<int>()}");
    }
);

Providing the option -o but without a value in the CLI invocation (which is legal, because the option's arity is ZeroOrOne),

rootCmd.Parse(new string[] {"-o"}).Invoke();

will lead to the following unexpected behavior

Actual behavior

The DefaultValueFactory is not being executed, rather the int type default value is being assumed, resulting in the output:

Value: 0

Expected behavior

I would expect the DefaultValueFactory being executed to provide the default value also in case the -o option is given without a value in the CLI, giving the following output:

DefaultValueFactory called
Value: 42

(My apologies to anyone that got the first incomplete and broken version of my issue report. It seems to be a good idea to not let me be near Enter keys...)

Activity

  1. changed the title [-]Option with Arity of ZeroOrOne or ZeroOrMore don'and DefaultValueFactory?[/-] [+]Option with Arity of ZeroOrOne or ZeroOrMore don't use DefaultValueFactory when option is given without value on the CLI[/+] on Aug 6, 2023
  2. elgonzo commented on Jun 21, 2025

    @elgonzo
    ContributorAuthor

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

  3. added this to the Triage milestone on Jun 23, 2025
  4. self-assigned this
    on Jul 9, 2025
  5. added 2 commits that reference this issue on Aug 8, 2025
    7154d16
    0b4618b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions