Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of enum values and descriptions?

Tags:

enums

I have the following enum:

public enum AlertSeverity
    {
        [Description("Informative")]
        Informative = 1,

        [Description("Low risk")]
        LowRisk = 2,

        [Description("Medium risk")]
        MediumRisk = 3,

        [Description("High risk")]
        HighRisk = 4,

        Critical = 5
    }

and I want to get a List<KeyValuePair<string, int>> of all the description / names and values, so I tried something like this:

public static List<KeyValuePair<string, int>> GetEnumValuesAndDescriptions<T>() where T : struct
    {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new InvalidOperationException();
        List<KeyValuePair<string, int>> lst = new List<KeyValuePair<string, int>>();
        foreach (var field in type.GetFields())
        {
            var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; // returns null ???
            if (attribute != null)
                lst.Add(new KeyValuePair<string, int>(attribute.Description, ((T)field.GetValue(null)).ToInt()));
            else
                lst.Add(new KeyValuePair<string, int>(field.Name, ((T)field.GetValue(null)).ToInt())); // throws exception: "Non-static field requires a target" ???
        }
        return lst;
    }

I don't know why but the attribute var returns null and the field.Name throws exception "Non-static field requires a target"

like image 629
Liran Friedman Avatar asked Jan 15 '15 07:01

Liran Friedman


1 Answers

This should work:

public static List<KeyValuePair<string, int>> GetEnumValuesAndDescriptions<T>()
        {
            Type enumType = typeof (T);

            if (enumType.BaseType != typeof(Enum))
                throw new ArgumentException("T is not System.Enum");

            List<KeyValuePair<string, int>> enumValList = new List<KeyValuePair<string, int>>();

            foreach (var e in Enum.GetValues(typeof(T)))
            {
                var fi = e.GetType().GetField(e.ToString());
                var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

                enumValList.Add(new KeyValuePair<string, int>((attributes.Length > 0) ? attributes[0].Description : e.ToString(), (int)e));
            }

            return enumValList;
        }
like image 97
Giorgi Nakeuri Avatar answered Nov 15 '22 07:11

Giorgi Nakeuri