Tuesday, February 5, 2008

Revision# 6,450,002.0 of the command line parameter parsing piece

One of the most re-invented wheels of all time is the one which takes options from a set of command line arguments. It's a fine tradition to reinvent this wheel and here I present the fruits of today's celebration.
static void Main(string[] args)
{
    string option1 = getCommandLineParameter("-option1", args);
    string option2 = getCommandLineParameter("-option2", args);

    if (option1 != null && option2 != null)
    {
        // react to these parameters
    }
    else
    {
        // react to these parameters not being given
    }
}


private static string getCommandLineParameter(string optionName, string[] args)
{
    short i;
    for (i = 0; i < args.Length; i++)
    {
        if (args[i] == optionName)
        {
            if (args[i + 1] != null)
            {
                return args[i + 1];
            }
            else
            {
                return null;
            }
        }
    }

    return null;
}

No comments: