Search code examples
c#system.commandlinesystem.commandline.dragonfruit

How can I define an enum as CLI option with System.CommandLine.DragonFruit?


I'd like to define an enum as CLI option in C# System.CommandLine.DragonFruit. Is there "builtin" support for this use case? In detail I need an equivalent to Python's click implementation of this:

@click.option('-m', '--mode', required=True, type=click.Choice(['SIM_MRM', 'SPECTRUM'], case_sensitive=True), help="The measurement mode.")

If I define the following in the C# console app

using System;

namespace EndDeviceAgent
{
    class Program
    {
        enum MeasurementMode : short
        {
            SIM_MRM,
            SPECTRUM
        }

        /// <param name="mode">The measurement mode.</param>
        static void Main(MeasurementMode mode)
        {
            Console.WriteLine($"Mode: {mode}");
        }
    }
}

I get Mode: SIM_MRM as output. However instead I'd like to get an exception cause the option is required and I don't want the default implied by the enum.


Solution

  • I don't know System.CommandLine, but a simple way may be to add a default to the enum and to check mode at the beginning to throw an exception:

    enum MeasurementMode
    {
      NONE,
      SIM_MRM,
      SPECTRUM
    }
    
    static void Main(MeasurementMode mode)
    {
      if ( mode == MeasurementMode.None ) 
        throw new ArgumentException("A mode value other than NONE must be provided.");
    
      Console.WriteLine($"Mode: {mode}");
    }
    

    Maybe a better solution exists, such as an attribute to apply the requirement, so that you can inspect documentation or source code if you have time.

    I removed the short keyword because it isn't needed, unless you have a good reason to use it (takes by default 4 bytes anyway on any x32/x64 system).