A lovely piece of code for dealing with parameters in C#

October 7, 2008

I can’t claim credit for this, as I saw it yesterday whilst receiving a demo of a (very good) messaging architecture written by another developer.  It’s only a little scrap of code, but that makes it even better: its beauty is its simplicity.  So, to get parameters out of some parameter holding class, but to not have to (a) make everything the same type or; (b) have N methods for retrieving N types, you can do this:

    public class Params
        Dictionary _values = new Dictionary();

        public Params()

        public T GetParam(string name, T defaultValue)
            if (_values.ContainsKey(name) == false)
                return defaultValue;
            return (T)_values[name];

Which you then call like this:

            Params p = new Params();
            int key1 = p.GetParam("key1", 39);
            string key2 = p.GetParam("key2", "defaultValue");
            double key3 = p.GetParam("key3", 44.2);

Leave a Reply

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

WordPress.com Logo

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: