Skip to content

Instantly share code, notes, and snippets.

@huyderman
Created February 20, 2012 13:26
Show Gist options
  • Save huyderman/1869189 to your computer and use it in GitHub Desktop.
Save huyderman/1869189 to your computer and use it in GitHub Desktop.
private static readonly Type StringType = typeof(string);
private static readonly Dictionary<Type, bool> IsStringAssignable = new Dictionary<Type, bool> { { StringType, true } };
private static readonly Dictionary<Type, ConstructorInfo> SingleStringConstructor = new Dictionary<Type, ConstructorInfo>();
private static readonly Dictionary<Type, MethodInfo> ParseMethod = new Dictionary<Type, MethodInfo>();
public static T Get<T>(string setting)
{
object value = ConfigurationManager.AppSettings.Get(setting);
if (value == null)
return default(T);
var t = typeof(T);
if (!IsStringAssignable.ContainsKey(t))
IsStringAssignable[t] = t.IsAssignableFrom(StringType);
if (IsStringAssignable[t])
return (T)value;
if (!SingleStringConstructor.ContainsKey(t))
SingleStringConstructor[t] = t.GetConstructors().SingleOrDefault(HasSingleArgument<string>);
if (SingleStringConstructor[t] != null)
{
return (T)SingleStringConstructor[t].Invoke(new[] { value });
}
if (!ParseMethod.ContainsKey(t))
{
ParseMethod[t] = t.GetMethods().SingleOrDefault(IsParseMethod);
}
if (ParseMethod[t] != null)
{
return (T)ParseMethod[t].Invoke(null, new[] { value });
}
return default(T);
}
private static bool IsParseMethod(MethodInfo m)
{
return m.Name == "Parse" && m.IsStatic && HasSingleArgument<string>(m) && m.ReturnType == StringType;
}
private static bool HasSingleArgument<T>(MethodBase method)
{
var parameters = method.GetParameters();
return parameters.Count() == 1 && parameters.First().ParameterType == typeof(T);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment