Oct 27 2006
appSettings, type-safety and default values — all in 5 minute’s work
I recently wanted to have a method I could call to get a type-safe AppSetting, with an optional default value if the AppSetting wasn’t set. In C# 2.0, I came up with this:
public static T GetSetting<T>(string name, T defaultValue)
{
string input = ConfigurationManager.AppSettings[name];
if (input != null)
{
return (T)Convert.ChangeType(input, typeof(T));
}
else
{
return defaultValue;
}
}
Related posts

























Very neat use of the GetType method, didnt realise it was there until now.
Just to add some value Ive refactored the code below so that it also checks for both empty and null, also removed the else (but thats just coding style).
///
/// Gets the setting.
///
/// The name.
/// The default value.
/// The type
public static T GetSetting(string name, T defaultValue)
{
string input = ConfigurationManager.AppSettings[name];
if (! String.IsNullOrEmpty(input))
{
return (T) Convert.ChangeType(input, typeof(T));
}
return defaultValue;
}
Thanks for the code snippet, Im sure Ill find a neat way to incorporate it into a base class.
Cheers
Sonny M
Hi Seth,
Not sure if it’s by design or a bug but the Convert.ChangeType method doesn’t handle nullable types.
The below link goes into more depth into the problem and possible solution, but the supporting sample isn’t coded for web environment.
http://72.14.253.104/search?q=cache:WWFbc_Zt-eIJ:blog.pumacode.org/+Convert.ChangeType+nullable+type+error&hl=en&gl=au&ct=clnk&cd=4
I’ll try and post a solution, but thats if you don’t do it first.
Cheers
Sonny M