Mike
Mike

Reputation: 167

Command Line Parser library giving 'System.Type' error in C#

I'm writing a Console App (.NET Framework) in C#. I want to use arguments from the command line, and I'm trying to use the Command Line Parser library to help me do this.

This is the package on Nuget - https://www.nuget.org/packages/CommandLineParser/

I found out about it from this StackOverflow question - Best way to parse command line arguments in C#?

MWE

using System;
using CommandLine;

namespace CLPtest
{
    class Program
    { 

        class SomeOptions
        {
            [Option('n', "name")]
            public string Name { get; set; }

        }

        static void Main(string[] args)
        {

            var options = new SomeOptions();

            CommandLine.Parser.Default.ParseArguments(args, options);

        }
    }
}

When I try create a minimal working example, I get an error for options on this line:

CommandLine.Parser.Default.ParseArguments(args, options);

The error is Argument 2: cannot convert from 'CLPtest.Program.SomeOptions' to 'System.Type'

I'm really confused as I have seen this same example code on at least 3 tutorials for how to use this library. (see for example - Parsing Command Line Arguments with Command Line Parser Library)

Upvotes: 1

Views: 2493

Answers (1)

cGilmore
cGilmore

Reputation: 11

(This answer is being written at the time of v2.7 of this library)

From looking at their repository's README, it appears as if this is part of the API change that is mentioned earlier in the README. It looks as though the arguments are now handled differently since the example code you reference. So, now you should do something like this inside of Main:

...

static void Main(string[] args)
{
    CommandLine.Parser.Default.ParseArguments<SomeOptions>(args);
}

...

To actually do something with those options you can use WithParsed which takes in the options that are defined in your SomeOptions class.

...

static void Main(string[] args)
{
    CommandLine.Parser.Default.ParseArguments<SomeOptions>(args).WithParsed(option =>
    {
        // Do something with your parsed arguments in here...

        Console.WriteLine(option.Name); // This is the property from your SomeOptions class.
    });
}

...

The C# Example further down the README shows that you can pass in a method into WithParsed to handle your options instead of doing everything within Main.

Upvotes: 1

Related Questions