dotnet / dotnet/command-line-api
Command handler breaking changes not updated in doc
- Dominant language
- C#
- Stars
- 3.7k
- Forks
- 428
- PR merge metrics
- No merged PRs in 30d
Description
The https://github.com/dotnet/command-line-api/blob/main/docs/How-To.md#pass-parameters-to-a-method doc prescribes this:
```cs
static async Task Main(string[] args)
{
var rootCommand = new RootCommand();
rootCommand.Add(new Option("--an-int"));
rootCommand.Add(new Option("--a-string"));
rootCommand.SetHandler((int i, string s) => DoSomething(i, s));
await rootCommand.InvokeAsync(args);
}
public static void DoSomething(int anInt, string aString)
{
/* do something */
}
```
But this fails at runtime with:
> Unhandled exception: System.ArgumentException: Service not found for type System.Int32.
With quite a bit of trial and error, I learned that I can get it to work with the latest version by storing each option in a local so I can also pass it to the `SetHandler` method:
```cs
using System.CommandLine;
var intOption = new Option("--an-int");
var stringOption = new Option("--a-string");
var rootCommand = new RootCommand
{
intOption,
stringOption,
};
rootCommand.SetHandler((int i, string s) => DoSomething(i, s), intOption, stringOption);
await rootCommand.InvokeAsync(args);
static void DoSomething(int anInt, string aString)
{
/* do something */
}
```
But this feels overly verbose. Why must I tell the same command about each option *twice* for it to work? Why can't the handler default to the options and ordering as provided to the command itself?
Anyway, the docs and the latest release on nuget.org are out of sync. Please update one of them.
Contributor guide
Assessment
This issue has not been assessed yet.