Skip to content

Instantly share code, notes, and snippets.

@elusive
Last active May 23, 2018 12:21
Show Gist options
  • Save elusive/6e3b40046c02cb6fc195d6ac5d4172cc to your computer and use it in GitHub Desktop.
Save elusive/6e3b40046c02cb6fc195d6ac5d4172cc to your computer and use it in GitHub Desktop.
Enum<T> Extensions
// From the OpenRA Game Engine I was reading the code and found this nice enum ext!
public static class Enum<T>
{
public static T Parse(string s) { return (T)Enum.Parse(typeof(T), s); }
public static T[] GetValues() { return (T[])Enum.GetValues(typeof(T)); }
public static bool TryParse(string s, bool ignoreCase, out T value)
{
// The string may be a comma delimited list of values
var names = ignoreCase ? Enum.GetNames(typeof(T)).Select(x => x.ToLowerInvariant()) : Enum.GetNames(typeof(T));
var values = ignoreCase ? s.Split(',').Select(x => x.Trim().ToLowerInvariant()) : s.Split(',').Select(x => x.Trim());
if (values.Any(x => !names.Contains(x)))
{
value = default(T);
return false;
}
value = (T)Enum.Parse(typeof(T), s, ignoreCase);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment