Skip to content

Instantly share code, notes, and snippets.

@mat-mcloughlin
Created July 18, 2015 20:49
Show Gist options
  • Save mat-mcloughlin/537e44fd704e6061deef to your computer and use it in GitHub Desktop.
Save mat-mcloughlin/537e44fd704e6061deef to your computer and use it in GitHub Desktop.
WTF???
public class Settings
{
public Settings()
{
SomeString = Helpers.GetSetting("SomeString", "DefaultString");
SomeInt = Helpers.GetSetting("SomeInt", 9, int.TryParse);
SomeTimeSpan = Helpers.GetSetting("SomeTimeSpan", new TimeSpan(60), Helpers.TimeSpanParser);
}
public string SomeString { get; set; }
public int SomeInt { get; set; }
public TimeSpan SomeTimeSpan { get; set; }
}
public static class Helpers
{
public static T GetSetting<T>(string appSetting, T @default, TryParseHandler<T> handler) where T : struct
{
var value = ConfigurationManager.AppSettings[appSetting];
if (string.IsNullOrEmpty(value))
{
return @default;
}
T result;
if (handler(value, out result))
{
return result;
}
throw new Exception(); // Swap to something better :)
}
public static string GetSetting(string appSetting, string @default)
{
return ConfigurationManager.AppSettings[appSetting];
}
public static bool TimeSpanParser(string value, out TimeSpan result)
{
result = TimeSpan.FromSeconds(double.Parse(value));
return true;
}
public delegate bool TryParseHandler<T>(string value, out T result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment