Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert generic T into System.Enum

Tags:

c#

enums

I have a list of Enums 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?

like image 400
user3340627 Avatar asked Nov 24 '14 09:11

user3340627


1 Answers

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
like image 151
WeHaveCookies Avatar answered Oct 13 '22 12:10

WeHaveCookies