Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get string list of Enum descriptions? [duplicate]

Tags:

c#

types

enums

How can I get a List of an Enum's values?

For example, I have the following:

public enum ContactSubjects
{
    [Description("General Question")]
    General,
    [Description("Availability/Reservation")]
    Reservation,
    [Description("Other Issue")]
    Other
}

What I need to be able to do is pass ContactSubject.General as an argument and it returns the List of the descriptions.

This method needs to work with any Enum, not just ContactSubject (in my example). The signature should be something like GetEnumDescriptions(Enum value).

like image 656
kodikas Avatar asked Oct 24 '12 22:10

kodikas


1 Answers

Something like that may work:

    private static IEnumerable<string> GetDescriptions(Type type)
    {
        var descs = new List<string>();
        var names = Enum.GetNames(type);
        foreach (var name in names)
        {
            var field = type.GetField(name);
            var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
            foreach (DescriptionAttribute fd in fds)
            {
                descs.Add(fd.Description);
            }
        }
        return descs;
    }

however you may review some logic there: such as is it ok to start of names? how are you going to handle multiple Description attributes? What if some of them are missing - do you want a name or just skip it like above? etc.

just reviewed your question. For the VALUE you would have something like that:

private static IEnumerable<string> GetDescriptions(Enum value)
{
    var descs = new List<string>();
    var type = value.GetType();
    var name = Enum.GetName(type, value);
    var field = type.GetField(name);
    var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
    foreach (DescriptionAttribute fd in fds)
    {
        descs.Add(fd.Description);
    }
    return descs;
}

however it is not possible to place two Description attributes on single field, so I guess it may return just string.

like image 51
aiodintsov Avatar answered Oct 23 '22 16:10

aiodintsov