Command Line Params

This is a simple class that I use for parsing command line params.

CommandLineParams clp = new CommandLineParams();
string server = clp["/s"];
bool test = clp.Contains("/test");

When the class is constructed for the first time I parse all command line parameters and save them in a dictionary. Then I can check if a parameter exists and access it using an indexer.

I chose to make the dictionary static so I don’t parse the parameters every time. I don’t feel great about it but I’ll leave it like this for now. It would be perfect if there were static indexers, then the code at least would have been prettier…

Here is the complete source code:

public class CommandLineParams
    private static Dictionary dict;

    public string this[string key] { get { return dict[key]; } }

    public bool Contains(string key)
        return dict.ContainsKey(key);

    public CommandLineParams()
        if (dict == null)
            dict = new Dictionary();

            string[] args = System.Environment.GetCommandLineArgs();

            foreach (string s in args)
                string ParamName, ParamValue;
                if (ParsePair(s, out ParamName, out ParamValue))
                    dict.Add(ParamName, ParamValue);
                    dict.Add(s, string.Empty);

    // TODO: refactor using RegEx
    bool ParsePair(string Pair, out string Name, out string Value)
        int pos = Pair.IndexOf("=");
        if (pos >= 0)
            Name = Pair.Remove(pos, Pair.Length - pos);
            Value = Pair.Remove(0, pos + 1);
            return true;

        // otherwise
        Name = string.Empty;
        Value = string.Empty;
        return false;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s