Skip to content

Instantly share code, notes, and snippets.

@crlspe
Last active March 23, 2017 22:43
Show Gist options
  • Save crlspe/3f5d2c611da8ff91e045ab198f4d5e7b to your computer and use it in GitHub Desktop.
Save crlspe/3f5d2c611da8ff91e045ab198f4d5e7b to your computer and use it in GitHub Desktop.
public static T Parse<T>(string value)
{
return (T)Enum.Parse(typeof(T), value, true);
}
public static IEnumerable<T> GetValues<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
public static Dictionary<string, int> GetEnumList<T>()
{
Type enumType = typeof(T);
if (!enumType.IsEnum) throw new Exception("Type parameter should be of enum type");
return Enum.GetValues(enumType).Cast<int>().ToDictionary(v => Enum.GetName(enumType, v), v =>v );
}
public static string Description(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
else
{
return value.ToString();
}
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment