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
Code:
bool b;
string s = ConfigurationManager.AppSettings["SomeKey"];
if (s != null)
b = Convert.ToBoolean(s);
So first I made this shorter by creating an alias for ConfigurationManager.AppSettings.
NameValueCollection settings = ConfigurationManager.AppSettings;
and then you can call
Code:
strings s = settings["SomeKey"];
if (s != null) b = Convert.ToBoolean(s);
But this still has the conversion functions and the checking for null all over the place.
So I created a generic extension method for NameValueCollection which is the type of AppSettings.
Code:
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;
}
and now you can just call
Code:
bool b = settings.Get<bool>("SomeKey", false);
Hope you like it.
Cheers