Skip to content

Instantly share code, notes, and snippets.

@simoneb
Last active January 7, 2020 07:34
Show Gist options
  • Save simoneb/3818255 to your computer and use it in GitHub Desktop.
Save simoneb/3818255 to your computer and use it in GitHub Desktop.
Simple dynamic command line arguments parser
class Options : DynamicObject
{
readonly IDictionary<string, object> inner = new ExpandoObject();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (!inner.TryGetValue(binder.Name, out result))
result = false;
else
result = result != null ? new OptionValue(result.ToString()) : (dynamic)true;
return true;
}
public static Options Parse(string[] args)
{
return args.Select(s => s.Split(new[] {'='}))
.Aggregate(new Options(), (d, s) =>
{
d.inner[s[0]] = s.Length > 1 ? s[1] : null;
return d;
}, d => d);
}
class OptionValue : DynamicObject
{
private readonly string value;
public OptionValue(string value)
{
this.value = value;
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
bool _;
if(binder.ReturnType == typeof(bool) && !bool.TryParse(value, out _))
result = true;
else
result = TypeDescriptor.GetConverter(binder.ReturnType).ConvertFromInvariantString(value);
return true;
}
}
}
dynamic options = Options.Parse(new[]{"flag1", "flag2=1", "flag3=someString"});
Console.WriteLine("Is there flag1? {0}", options.flag1);
Console.WriteLine("flag1 value: {0}", options.flag1);
Console.WriteLine("Is there flag2? {0}", (bool)options.flag2);
Console.WriteLine("flag2 value: {0}", (int)options.flag2);
Console.WriteLine("Is there flag3? {0}", (bool)options.flag3);
Console.WriteLine("flag3 value: {0}", (string)options.flag3);
Console.WriteLine("Is there flag4? {0}", options.flag4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment