Skip to content

Instantly share code, notes, and snippets.

@nerdybeast
Last active November 27, 2017 18:08
Show Gist options
  • Save nerdybeast/bcca552bd4dd506dba6dc5d187404021 to your computer and use it in GitHub Desktop.
Save nerdybeast/bcca552bd4dd506dba6dc5d187404021 to your computer and use it in GitHub Desktop.
Cast app settings from web config in one shot
//Make this class static so that it is loaded in memory when the app starts
public static class AppSettings {
public static T Get<T>(string key) {
var appSetting = ConfigurationManager.AppSettings[key];
if (string.IsNullOrWhiteSpace(appSetting)) throw new AppSettingNotFoundException(key);
var converter = TypeDescriptor.GetConverter(typeof(T));
return (T)(converter.ConvertFromInvariantString(appSetting));
}
}
//In another class use like:
var isProd = AppSettings.Get<bool>("IsProd");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment