Last active
November 27, 2017 18:08
-
-
Save nerdybeast/bcca552bd4dd506dba6dc5d187404021 to your computer and use it in GitHub Desktop.
Cast app settings from web config in one shot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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
Thanks to https://stacktoheap.com/blog/2013/01/20/using-typeconverters-to-get-appsettings-in-net/