Skip to content

Instantly share code, notes, and snippets.

@carstencodes
Created May 4, 2021 13:29
Show Gist options
  • Save carstencodes/742d370b56766aaa5fec64959aae6f03 to your computer and use it in GitHub Desktop.
Save carstencodes/742d370b56766aaa5fec64959aae6f03 to your computer and use it in GitHub Desktop.
Example for an erroneous run for the command line parser
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="commandlineparser" Version="2.8.0" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using CommandLine;
namespace calc
{
[Verb("fib")]
internal sealed class FibonacciOption
{
[Value(0, Required = true, MetaName = "position of the fibonacci number to calculate" )]
public uint Position { get; set; }
}
[Verb("square")]
internal sealed class SquareOption
{
[Value(0, Required = true, MetaName = "value to create a square of")]
public uint Value {get; set;}
}
class Program
{
static int Main(string[] args)
{
using (Parser parser = new Parser(ConfigureParser))
{
return parser.ParseArguments<FibonacciOption, SquareOption>(args).MapResult(
(FibonacciOption fo) => HandleFibonacciOption(fo),
(SquareOption so) => HandleSquareOption(so),
err => HandleErrors(err));
}
}
private static void ConfigureParser(ParserSettings settings)
{
settings.AutoHelp = true;
settings.AutoVersion = true;
settings.HelpWriter = System.Console.Out;
settings.IgnoreUnknownArguments = false;
}
private static int HandleErrors(IEnumerable<Error> _)
{
return 1;
}
private static int HandleFibonacciOption(FibonacciOption option)
{
Console.Out.WriteLine("Calculate {0}-th fibonacci number", option.Position);
uint fibonacci = Fibonacci(option.Position);
Console.Out.WriteLine(fibonacci);
return 0;
}
private static int HandleSquareOption(SquareOption option)
{
Console.Out.WriteLine("Calculate square of {0}", option.Value);
Console.Out.WriteLine(option.Value * option.Value);
return 0;
}
private static uint Fibonacci(uint position)
{
switch (position)
{
case 0u:
case 1u:
{
return 1u;
}
default:
{
return Fibonacci(position - 1) + Fibonacci(position - 2);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment