Retrieving Application Settings

Here is a safe, generic way to retrieve application settings.

public static T GetAppSetting<T>(string key)
   if (ConfigurationManager.AppSettings.AllKeys.Contains(key))
      return (T)System.Convert.ChangeType(ConfigurationManager.AppSettings[key], 
                                        typeof(T), CultureInfo.InvariantCulture);
      return default(T);


int serverPort = GetAppSetting<int>("server_port");

One thought on “Retrieving Application Settings

  1. What is the default() method, and what would it do? How would it know what value to return if it’s only based on type? Are we to assume that all int values have the same default, etc?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s