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);
   }
   else
   {
      return default(T);
   }
}

Usage

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?

Comments are closed.