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

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.