Skip to content

Instantly share code, notes, and snippets.

@danesparza
Created January 12, 2016 19:08
Show Gist options
  • Save danesparza/ec63bad5d36c698efc65 to your computer and use it in GitHub Desktop.
Save danesparza/ec63bad5d36c698efc65 to your computer and use it in GitHub Desktop.
C# configuration manager
/// <summary>
/// Simple manager for config items
/// </summary>
public static class ConfigManager
{
/// <summary>
/// Get the config value for the given key/name
/// </summary>
/// <typeparam name="T">The expected type of the config values</typeparam>
/// <param name="configKey">The configuration key to get</param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static T GetConfig<T>(string configKey, T defaultValue = default(T))
{
T results = defaultValue;
// By default, just use the app config file to get configuration data:
if(!string.IsNullOrEmpty(configKey))
{
// First get the string value:
string stringvalue = ConfigurationManager.AppSettings[configKey];
try
{
// Make sure the returned value isn't null or empty
if(!string.IsNullOrEmpty(stringvalue))
{
var theType = typeof(T);
// If we're expecting an enumerated type...
if(theType.IsEnum)
{
// attempt to cast to the enum:
results = (T)Enum.Parse(theType, stringvalue, true);
}
else
{
// Otherwise, just cast to the type
results = (T)Convert.ChangeType(stringvalue, theType);
}
}
}
catch { /* Just fall through to the defaults */ }
}
return results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment