Parsing Command Line Arguments with Command Line Parser Library

When writing .Net console applications we often need to parse command line arguments that the user specified when launching the application.

We get these arguments passed into the program in the args parameter of Main()

static void Main(string[] args)

If our application only has a single simple parameter then it’s probably ok to just parse it ourselves.

Once the number and type of parameters increase then there’s a whole host of complexity that can creep in:

  • What if values need converting to enum values?
  • How to handle arguments that takes a list of values?
  • How to implement verb style arguments like “git push”?
  • What if parameters are in different order?
  • What about optional parameters and should we use default values if they’re not supplied?
  • What about arguments that are mutually exclusive?

While we can program our console applications to account for these things it could be quite a lot of work and testing to implement effectively.

It makes sense in these cases to use a ready-built library such as Command Line Parser Library.

Command Line Parser Library Basics

This library represents arguments by creating a class and decorating its properties that represent args with the [Option] attribute.

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

    [Option('a', "age")]
    public int Age { get; set; }

Here this class is stating that we should always have a name argument (Required=true) and we can specify it at the command line with the shorthand “-n” or longer --name”.

The age argument is optional and can be specified with “-a” or --age”.

So from the command line we could type:

myconsoleapplication.exe -n Jason --age 99

In our Main method we can now parse these arguments into  an instance of our SomeOptions class.

static void Main(string[] args)
    var options = new SomeOptions();

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

    // options.Name will = Jason
    // options.Age will = 99

The ParseArguments method takes the array of string args from the command line and populates our SomeOptions instance which we can then use in a strongly typed way.

There’s a lot more to this library such as implementing verb style arguments, strict parsing, and creating help text, all of which I cover in my Pluralsight Building .NET Console Applications in C# course.


Add comment