No question in this post, just something you might put to good use too:
I got sick of this code that uses Configurationmanager all over the place
So first I made this shorter by creating an alias for ConfigurationManager.AppSettings.Code:bool b; string s = ConfigurationManager.AppSettings["SomeKey"]; if (s != null) b = Convert.ToBoolean(s);
NameValueCollection settings = ConfigurationManager.AppSettings;
and then you can call
But this still has the conversion functions and the checking for null all over the place.Code:strings s = settings["SomeKey"]; if (s != null) b = Convert.ToBoolean(s);
So I created a generic extension method for NameValueCollection which is the type of AppSettings.
and now you can just callCode:public static T Get<T>(this NameValueCollection cm, string index, T def) { T ret = def; string s = cm[index]; if (s != null) ret = (T)Convert.ChangeType(cm[index], typeof(T)); return ret; }
Hope you like it.Code:bool b = settings.Get<bool>("SomeKey", false);
Cheers



LinkBack URL
About LinkBacks



