Over a million developers have joined DZone.

Get AppSettings from web.config in a generic way

DZone's Guide to

Get AppSettings from web.config in a generic way

Free Resource

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: -->
    <add key="Title" value="Web title" />
    <add key="VersionNumber" value="5" />
    <add key="UseThemes" value="True" />
    <add key="WebTheme" value="Light" />

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

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)
                if (throwExceptions)
public static T GetAppSetting
  (string key, T defaultValue)
    if (!string.IsNullOrEmpty(key))
        string value = ConfigurationManager.AppSettings[key];
            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;

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}