Skip to content

Instantly share code, notes, and snippets.

@chillitom
Created June 11, 2010 10:02
Show Gist options
  • Save chillitom/434306 to your computer and use it in GitHub Desktop.
Save chillitom/434306 to your computer and use it in GitHub Desktop.
public static class EnumUtils
{
public static IEnumerable<T> Values<T>()
{
CheckTypeParamIsEnum<T>();
return Enum.GetValues(typeof(T)).Cast<T>();
}
public static T ToEnum<T>(int value)
{
CheckTypeParamIsEnum<T>();
Ensure.ArgumentValid(Enum.IsDefined(typeof(T), value),
"value",
value + " is not a valid value for enumeration " + typeof(T));
return (T) Enum.ToObject(typeof(T), value);
}
public static T Parse<T>(string value)
{
CheckTypeParamIsEnum<T>();
return (T) Enum.Parse(typeof(T), value);
}
public static T? ParseNullable<T>(string value) where T : struct
{
CheckTypeParamIsEnum<T>();
if(Enum.IsDefined(typeof(T), value))
{
return (T) Enum.Parse(typeof(T), value);
}
return null;
}
private static void CheckTypeParamIsEnum<T>()
{
if (!(typeof(Enum).IsAssignableFrom(typeof(T))))
{
throw new ArgumentException("Enum type expected");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment