Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access unbound parameters in C# CommandLine Parser by gsscoder?

There's a CommandLine parser library for C# written by gsscoder (it has its own SO tag and I'm adding it). It parses command-line options in getopt style, i.e.:

myprogram --foo --bar=baz abc def ghi

It can also have so called “unbound” parameters, i.e freestanding positional parameters that are not bound to options; in the example above these are abc, def, and ghi. Unfortunately, the documentation only mentions that “the parser has its means to handle these,” but doesn't give an example. And my C# is not that sharp so I'm intimidated by the amount of source code to scan to find it out.

Could someone please give an example of how to access these unbound parameters after parsing?

like image 649
Mikhail Edoshin Avatar asked Mar 08 '16 16:03

Mikhail Edoshin


1 Answers

use the ValueList[Attribute] (see docs on CodePlex):

Each value not captured by an option can be included in a collection of strings derived from System.Collections.Generic.IList.

Obviously, this attribute has no name(s) and is derived directly from System.Attribute. It's currently the only exception, but it's not excluded that in the future it will have similars.

Example (from page linked above):

class Options
{
  // ...
  [ValueList(typeof(List<string>), MaximumElements = 3)]
  public IList<string> Items { get; set; };
  // ...
}

where the ValueList

  1. Must be assigned to a property of type IList<string>.
  2. The constructor must accept a type derived from IList<string> as List<string>.
  3. If the MaximumElements property is set to a number greater than 0, the parser will fail if the limit is exceeded.
  4. Set MaximumElements to 0 means that you do not accept values disassociated from options.
  5. The default implicit setting of MaximumElements (-1) allows an unlimited number of values.
like image 160
russa Avatar answered Nov 09 '22 23:11

russa