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.

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?