dotnet / dotnet/command-line-api

Setting ArgumentArity on string Option disables Option's default value

Open
#1,010 3 comments 0 reactions 0 assignees View on GitHub
Area-API bug
Dominant language
C#
Stars
3.7k
Forks
428
PR merge metrics
No merged PRs in 30d

Description

Consider the following code

```csharp
using System;
using System.CommandLine;
using System.CommandLine.Invocation;

namespace zzCmdLineTest
{
class Program
{
static void Main(string[] args)
{
var command = new RootCommand
{
new Option("--a-string", getDefaultValue: () => "goodbye"),
new Option("--an-int")
};

command.Handler = CommandHandler.Create(
(string aString, int anInt) =>
{
Console.WriteLine(aString);
Console.WriteLine(anInt);
});

command.InvokeAsync(args);
}
}
}
```

Building, running and parsing gives the expected results with the default string value

```
C:\Code\zzCmdLineTest>dotnet run [parse]
[ zzCmdLineTest *[ --a-string ] ]

C:\Code\zzCmdLineTest>dotnet run
goodbye
0
```

Now change the code to add an Arity on the string parameter like this

```csharp
var command = new RootCommand
{
new Option("--a-string", getDefaultValue: () => "goodbye")
{ Argument = new Argument() { Arity = ArgumentArity.ZeroOrOne }},
new Option("--an-int")
};
```

Building, running and parsing shows that the default value for the string variable no longer applies

```
C:\Code\zzCmdLineTest>dotnet run [parse]
[ zzCmdLineTest ]

C:\Code\zzCmdLineTest>dotnet run

0
```

I would expect the default value to remain in tact whether or not I had explicitly set that the Option was optional.

Contributor guide

Open the contributing guide

Research direction

Start by running the supplied C# reproducer and compare parsing and invocation with and without ArgumentArity.ZeroOrOne on the string Option. Trace the option's default-value and argument-arity handling; done means the default "goodbye" remains effective when the option is omitted after explicitly setting ZeroOrOne.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
cli
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.