I\'m having some hard time with trying to be generic with enums. I\'ve read that it\'s not that simple, and I can\'t seem to find a solution.
I\'m trying to create a
I took the liberty of modifying some parts of the code, like changing the return types to more C# standard API return values.
You can watch it run here.
public static EnumDescription ConvertEnumWithDescription() where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("Type given T must be an Enum");
}
var enumType = typeof(T).Name;
var valueDescriptions = Enum.GetValues(typeof (T))
.Cast()
.ToDictionary(Convert.ToInt32, GetEnumDescription);
return new EnumDescription
{
Type = enumType,
ValueDescriptions = valueDescriptions
};
}
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
return attributes[0].Description;
return value.ToString();
}
public class EnumDescription
{
public string Type { get; set; }
public IDictionary ValueDescriptions { get; set; }
}