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");

Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

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 to Mike Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.