Example code:
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Collections.Generic;
class Program
{
static int Main(string[] args)
{
var rootCommand = new RootCommand
{
new Option<string>(alias: "--abc" ),
new Argument<List<string>>(name: "abcd"),
};
rootCommand.Handler = CommandHandler.Create<string, List<string>>(command);
return rootCommand.Invoke(args);
}
static void command(string abc, List<string> abcd)
{
Console.WriteLine("option = \"{0}\"", abc);
foreach (string argument in abcd)
{
Console.WriteLine("argument = \"{0}\"", argument);
}
}
}
The argument name abcd
contains the option name abc
at the beginning. When run with no option but an argument: dotnet run -- foo
an exception is thrown:
Unhandled exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
---> System.NullReferenceException: Object reference not set to an instance of an object.
This does not happen, when the option is used to (e.g. dotnet run -- --abc foo bar
).
Is this a bug or expected behavior because of wrong usage?
Edit after hint from @Caius Jard:
Testing references abc
and abcd
for null value does not help:
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Collections.Generic;
class Program
{
static int Main(string[] args)
{
var rootCommand = new RootCommand
{
new Option<string>(alias: "--abc" ),
new Argument<List<string>>(name: "abcd"),
};
rootCommand.Handler = CommandHandler.Create<string, List<string>>(command);
return rootCommand.Invoke(args);
}
static void command(string abc, List<string> abcd)
{
if (abc != null)
{
Console.WriteLine("option = \"{0}\"", abc);
}
if (abcd != null)
{
foreach (string argument in abcd)
{
Console.WriteLine("argument = \"{0}\"", argument);
}
}
}
}