Skip to content

Instantly share code, notes, and snippets.

@wkoch
Last active March 25, 2017 03:01
Show Gist options
  • Save wkoch/810591ccd45e97de8224c3be1954c70a to your computer and use it in GitHub Desktop.
Save wkoch/810591ccd45e97de8224c3be1954c70a to your computer and use it in GitHub Desktop.
C# Options Parser
using System;
using System.Collections.Generic;
namespace Haiku
{
public class Cli
{
public List<Command> Commands = new List<Command>();
private string Argument { get; set; }
private string Option { get; set; }
private Command Default { get; set; }
public void Parse(string[] args)
{
Argument = (args.Length > 0) ? args[0] : null;
Option = (args.Length > 1) ? args[1] : null;
if (Argument != null)
{
foreach (Command command in Commands)
if (command.Name.ToLower() == Argument.ToLower())
command.Execute();
// Console.WriteLine($"{command.Name}: {command.Description}");
}
else
{
Default.Execute();
}
}
public void DefaultCommand(Command command)
{
Default = command;
}
public void AddCommand(Command command)
{
try
{
Commands.Add(command);
}
catch (ArgumentException)
{
Console.WriteLine($"An element with Key \"{command.Name}\" already exists.");
}
}
}
}
using System;
namespace Haiku
{
public class Command
{
public string Name { get; set; }
public string Description { get; set; }
public Action Method { get; set; }
public void Execute()
{
Method();
}
}
}
using System;
namespace Haiku
{
class Program
{
static void Main(string[] args)
{
Cli cli = new Cli();
cli.AddCommand(new Command { Name = "New", Description = "Create a new project.", Method = New });
cli.AddCommand(new Command { Name = "Build", Description = "Builds the project.", Method = Build });
cli.DefaultCommand(new Command { Name = "Help", Description = "Prints the Help text.", Method = Help });
cli.Parse(args);
}
public static void New()
{
Console.WriteLine("Creating a new project.");
}
public static void Build()
{
Console.WriteLine("Building this project.");
}
public static void Help()
{
Console.WriteLine("Help Text.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment