I use an intersection over a small collection of help commands. If I constrain myself tightly to your question; it winds up looking like this:
static bool ShowHelpRequired(IEnumerable<string> args)
{
return args.Select(s => s.ToLowerInvariant())
.Intersect(new[] { "help", "/?", "--help", "-help", "-h" }).Any();
}
Broadening the scope (just a little); I wind up with a method called ParseArgs
that returns a boolean
that is true if either parsing failed or help is required. This method also has an out
parameter that stores parsed program parameters.
/// <summary>
/// Parses the arguments; sets the params struct.
/// </summary>
/// <param name="argv">The argv.</param>
/// <param name="paramStruct">The parameter structure.</param>
/// <returns>true if <see cref="ShowHelp"/> needed.</returns>
static bool ParseArgs(IEnumerable<string> argv, out ParamStruct paramStruct)
{
paramStruct = new ParamStruct();
try { /* TODO: parse the arguments and set struct fields */ }
catch { return false; }
return argv.Select(s => s.ToLowerInvariant()).Intersect(new[] { "help", "/?", "--help", "-help", "-h" }).Any();
}
This makes things very convenient in the main and allows for good separation between ShowHelp
and ParseArgs
.
if (!ParseArgs(argv, out parameters))
{
ShowHelp();
return;
}
Notes
- Instead of having
ParseArgs
in Main
one variation is to place the ParseArgs
method into parameters struct as a static method.
- The
catch
should only catch parsing exceptions; code does not reflect this.