dotnet / dotnet/command-line-api

Complex object binding sends in null if any argument is evaluates to null (even w/ default)

Open
#652 5 comments 0 reactions 0 assignees View on GitHub
Area-Parser and Binder
Dominant language
C#
Stars
3.7k
Forks
428
PR merge metrics
No merged PRs in 30d

Description

Hi there, thanks for adding support for complex object binding -- makes the handler code SO much cleaner.

During my refactor to complex, I noticed that whenever a single argument is null w/o a default supplied (or default null), the entire complex type gets passed in as null.

I don't think passing in null would ever be desirable -- either the parser needs to throw or pass in the "default" version of the object (using `default(T)` for each argument that comes in as null maybe?)

We have plenty of use cases where we allow the user to not provide an input and we pull it from a saved setting.

Here's a working example of the behavior:

```csharp
class Program
{
static void Main(string[] args)
{
var root = new RootCommand();

root.AddCommand(TestCommand.Instance);

root.InvokeAsync(args).Wait();
}
}

public class TestRequest
{
public TestRequest(string test1)
{
this.Test1 = test1;
}
public string Test1 { get; }
}

public static class TestCommand
{
public static Command Instance = GetTestCommand();
private static Command GetTestCommand()
{
var test = new Command("test");

//broken w/ default null
//test.AddOption(new Option("--test1")
//{
// Argument = new Argument(() => null)
//});

////broken w/o default
//test.AddOption(new Option("--test1")
//{
// Argument = new Argument()
//});

//works w/ empty string
test.AddOption(new Option("--test1")
{
Argument = new Argument(() => "")
});

test.Handler = CommandHandler.Create((TestRequest request) =>
{
var msg = request == null ? "I'm broken!" : "I work!";

Console.WriteLine(msg);
});

return test;
}
}
```

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.