jmarkman446
jmarkman446

Reputation: 156

Command Line Parser - Options that use arrays triggers exception that "Sequence contains no elements"

Using the most current version of the CommandLineParser library, and I have a handful of options. My goal is to edit an XML file with this command line application, though that will hopefully expand.

public class MyOptions
{
    [Option('h', "sayhello")]
    public string HelloMessage { get; set; }

    [Option('v', "versioninfo")]
    public string VersionInfo { get; set; }

    [Option('c', "changenode")]
    public string[] ChangeNode { get; set; }

    [Option('g', "getnode")]
    public string[] GetNode { get; set; }
}

When I debug the application in Visual Studio and pass it the following argument/value via Project Properties -> Debug -> Command line arguments:

--sayhello hello

The application throws an InvalidOperationException, saying that the sequence contains no elements. If I comment out the two options that are of type string[] (ChangeNode and GetNode) or change them to IEnumerable<string>, the program runs without issue, hitting the following code:

if (!string.IsNullOrEmpty(options.HelloMessage))
    Console.WriteLine($"The message is: {options.HelloMessage}");

printing out:

The message is: hello

Changing the options that are of type string[] to List<string> or setting those options to Required = false still throw the same exception. I don't have any qualms about casting the IEnumerable to another collection for the logic dealing with those options, but I'm not sure if this is proper practice; how do I use arrays/collections with CommandLineParser to avoid this? The documentation is very basic and doesn't go into a lot of detail about much of how the library works outside of a few "Quick Start" examples.

Upvotes: 7

Views: 2631

Answers (2)

Paul Barnes
Paul Barnes

Reputation: 27

I had the same issue, and was able to work around it like this:

private string[] _parametersArray = new string[0];

[Option("parameters")]
public IEnumerable<string> Parameters
{
    get { return _parametersArray; }
    set { _parametersArray = value.ToArray(); }
}
public string[] ParametersArray
{
    get { return _parametersArray; }
}

Upvotes: 0

Marc P
Marc P

Reputation: 56

It works for me, if I define a default value for the option:

    [Option(HelpText = "Optionally specify all processes to document separated by a comma ','.", Separator = ',', Default = new string[0])]
    public string[] ProcessesToDocument { get; set; } = new string[0];

Upvotes: 4

Related Questions