0

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);
            }
        }
    }
}
user3224237
  • 448
  • 6
  • 12
  • Turn on "break when thrown" so you catch the error as soon as it happens (Debug menu, Exceptions, tick next to CLR). Maybe abcd is null – Caius Jard Sep 17 '21 at 20:26
  • @CaiusJard Testing `abcd` for null value does not help. I'm working with vscode, does "break when thrown" work there too? – user3224237 Sep 17 '21 at 20:50

0 Answers0