Search code examples
c#command-line-arguments

Using Command Line to parse arguments


I am trying to use CommandLine to enable parsing parameters with my console application. I don't think I am using it correctly. I am trying to learn how to create different options, like -s for Symbol, and -d for Date. Here is my attempt:

public interface ICommandLineOption
    {
        string WhichOption { get; }
    }

[Verb("symbol", HelpText = "Symbol to test")]
public class SymbolCommand : ICommandLineOption
{
    public string WhichOption { get { return "Symbol"; } private set { } }

    [Option('s', "symbol", Required = true, HelpText = "Symbol To run backtest")]
    public string Symbol { get; set; }
    
}

[Verb("begin", HelpText = "Start date of test")]
public class BeginDateCommand : ICommandLineOption
{
    public string WhichOption { get { return "BeginDate"; } private set { } }

    [Option('d', "date", Required = true, HelpText = "Date to begin run of backtest")]
    public System.DateTime BeginDate { get; set; }
    
}

static void Main(string[] args)
{
    Parser.Default.ParseArguments<ICommandLineOption>(args).WithParsed<ICommandLineOption>(o =>
    {
        switch (o.WhichOption)
        {
            case "Symbol":
                {
                    var comm = o as SymbolCommand;
                    Console.WriteLine(comm.Symbol);
                    break;
                }
            case "BeginDate":
                {
                    var comm = o as BeginDateCommand;
                    Console.WriteLine(comm.BeginDate);
                    break;
                }
            default:
                break;
        }
    });
}

But this doesn't work:

Exception thrown: 'System.InvalidOperationException' in CommandLine.dll
An unhandled exception of type 'System.InvalidOperationException' occurred in CommandLine.dll
Type ICommandLineOption appears to be immutable, but no constructor found to accept values

Solution

  • This is easily achieved with the Nuget library CommandLineParser

    static void Main(string[] args)
    {
           Parser.Default.ParseArguments<CommandLineOptions>(args)
           .WithParsed<CommandLineOptions>(o =>
           {
                    Console.WriteLine(o.Symbol);
                    Console.WriteLine(o.Date);
           });
         ...
    }
    
    public class CommandLineOptions
    {
        [Option('s', "symbol", Required = true, HelpText = "Symbol To run backtest")]
        public string Symbol { get; set; }
    
        [Option('d', "date", Required = true)]
        public string Date { get; set; }
    
    }