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);
Advertisements