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 generic function, that for an enum type would return the description for each enum value. I want to keep it generic and not to duplicate this method for each enum type...
Here's what I have so far:
public static KeyValuePair<string, List<KeyValueDataItem>> ConvertEnumWithDescription<T>()
where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new Exception("Type given T must be an Enum");
}
var enumType = typeof(T).ToString().Split('.').Last();
var itemsList = Enum.GetValues(typeof(T))
.Cast<T>()
.Select(x => new KeyValueDataItem
{
Key = Convert.ToInt32(x),
Value = GetEnumDescription(Convert.ToInt32(x))
})
.ToList();
var res = new KeyValuePair<string, List<KeyValueDataItem>>(enumType, itemsList);
return res;
}
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
return attributes[0].Description;
return value.ToString();
}
The issue I'm currently having is that:
cannot convert from 'int' to 'System.Enum'
When I'm trying to call the function GetEnumDescription.
If I convert it to T:
Value = GetEnumDescription((T)(object)Convert.ToInt32(x));
This is the error I'm getting:
cannot convert from 'T' to 'System.Enum'