Get AppSettings from web.config in a generic way
public static T GetAppSetting<T>(string key, T defaultValue)
{
if (!string.IsNullOrEmpty(key))
{
string value = ConfigurationManager.AppSettings[key];
try
{
if (value != null)
{
var theType = typeof(T);
if (theType.IsEnum)
return (T)Enum.Parse(theType, value.ToString(), true);
return (T)Convert.ChangeType(value, theType);
}
return default(T);
}
catch { }
}
return defaultValue;
}
I use this snippet in all web projects where I need to get settings from the AppSettings section in web.config. This method (static or not) makes it easy and clean to get settings converted to the type I need. Also it enables default values to be fetched if the setting doesn't exist or can be converted to the specified type.
It can be used in different ways, like so;
<!-- Imagine we have these settings: -->
<appSettings>
<add key="Title" value="Web title" />
<add key="VersionNumber" value="5" />
<add key="UseThemes" value="True" />
<add key="WebTheme" value="Light" />
</appSettings>
And we could call it like this:
string title = GetAppSetting<string>("Title", "My title");
Even better, we could let the type be inferred from the second parameter and call it like this:
string title = GetAppSetting("Title", "My title");
int version = GetAppSetting("VersionNumber", 123);
bool useThemes = GetAppSetting("UseThemes", false);
We could also use enums, like so:
// Imagine this enum:
enum MyThemes
{
Light,
Dark,
Office
}
And this would easily be called like this:
MyThemes theme = GetAppSetting("WebTheme", MyThemes.Office);
This snippet could, of course, be extended with an overload for throwing exceptions, like so:
public static T GetAppSetting(string key, T defaultValue)
{
return GetAppSetting(key, defaultValue, false);
}
// New parameter: bool throwExceptions
public static T GetAppSetting(string key, T defaultValue, bool throwExceptions)
{
...
try
{
...
}
catch
{
if (throwExceptions)
throw;
}
...
}







Comments
Mario Sannum replied on Sat, 2012/10/20 - 6:33am
There is also an option you can do with the default value if you want deferred execution on it, by changing it to a Func<T>. This would be handy when the default value might have some logic that's heavy to execute.
For example:
public static T GetAppSetting(string key, Func<T> defaultValue) { ... return defaultValue(); }And you might call it like so:
var value = GetAppSetting("MySetting", () => MyClass.DoSomethingTimeConsuming()); // Or var value = GetAppSetting("MySetting", () => { var builder = new StringBuilder(); // Do heavy stuff here. return builder.ToString(); });And this way the heavy stuff would only be executed if the default value is needed.