Last active
August 29, 2015 13:57
-
-
Save Porges/9733909 to your computer and use it in GitHub Desktop.
If you didn't have Enum.(Try)Parse?
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
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