Created
June 11, 2010 10:02
-
-
Save chillitom/434306 to your computer and use it in GitHub Desktop.
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
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