I have a list of Enum
s as an IEnumerable<T>
and I need to loop on each item and get its description like this:
IEnumerable<T> values = (T[])Enum.GetValues(typeof(T));
foreach (Enum value in values)
{
String mylist = Common.MyExtensions.getEnumDescription(value);
}
...
public static string getEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
return attributes[0].Description;
}
else
return value.ToString();
}
This produces an error at the foreach section
cannot convert "T" to System.Enum.
Isn't IEnumerable
a list of System.Enum
in the first place?
What sort of cast can do the trick?
One way to do the cast is:
Enum enumValueError = (Enum)value;
//compiler error: Cannot convert type 'xxx' to 'System.Enum'
Enum enumValueNoError = value as Enum;
//no error, but enumValueNoError will be null if value is not an Enum
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With