Skip to content

Instantly share code, notes, and snippets.

@Porges
Last active August 29, 2015 13:57
Show Gist options
  • Save Porges/9733909 to your computer and use it in GitHub Desktop.
Save Porges/9733909 to your computer and use it in GitHub Desktop.
If you didn't have Enum.(Try)Parse?
static bool TryParseEnum<T>(string input, out T parsedValue)
{
input = input.Trim();
foreach (T value in Enum.GetValues(typeof(T)))
{
if (value.ToString() == input)
{
parsedValue = value;
return true;
}
}
parsedValue = default(T);
return false;
}
internal static class EnumCache<T>
{
internal static Dictionary<string, T> Cache;
}
static bool TryParseEnumFaster<T>(string input, out T parsedValue)
{
var cache = EnumCache<T>.Cache;
if (cache == null)
{
cache = new Dictionary<string, T>();
foreach (T value in Enum.GetValues(typeof(T)))
{
cache[value.ToString()] = value;
}
EnumCache<T>.Cache = cache;
}
return cache.TryGetValue(input, out parsedValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment