0

enter image description here

I was trying to get the enum description in this method.

Is there any way to get the enum description in this method? For example:

Enum.GetValues(typeof(T))
        .Cast<T>()
        .ToDictionary(t => (int)(object)t, t => t.Description.ToString());
  • Does this answer your question? [Getting attributes of Enum's value](https://stackoverflow.com/questions/1799370/getting-attributes-of-enums-value) – shingo Mar 28 '22 at 09:23
  • What are you asking exactly? You want to set enum descriptions to dictionary and the code you have shared already do this? – Berkay Yaylacı Mar 28 '22 at 09:43

1 Answers1

0

The following will provides descriptions for an enum.

public class EnumHelper
{
    public static List<KeyValuePair<string, Enum>> GetItemsAsDictionary<T>() =>
        Enum.GetValues(typeof(T)).Cast<T>()
            .Cast<Enum>()
            .Select(value => new KeyValuePair<string, Enum>(
                (GetCustomAttribute(value.GetType().GetField(value.ToString())!,
                    typeof(DescriptionAttribute)) as DescriptionAttribute)!.Description, value))
            .ToList();
}

Or with type checking

public static List<KeyValuePair<string, Enum>> GetItemsAsDictionarySafe<T>()
{
    if (!typeof(T).IsEnum)
    {
        throw new ArgumentException("Must be an enum");
    }
    return Enum.GetValues(typeof(T)).Cast<T>()
        .Cast<Enum>()
        .Select(value => new KeyValuePair<string, Enum>(
            (GetCustomAttribute(value.GetType().GetField(value.ToString())!, 
                typeof(DescriptionAttribute)) as DescriptionAttribute)!.Description, value))
        .ToList();
}

Sample Enum

public enum Shapes
{
    [Description("A shape with 3 strokes")]
    Triangle,
    [Description("A rounded shape")]
    Circle,
    [Description("A shape with 4 corners")]
    Square,
    [Description("Other option")]
    Other
}

Usage

Dictionary<string, Enum> dictionary = 
    new Dictionary<string, Enum>(EnumHelper.GetItemsAsDictionary<Shapes>());
Karen Payne
  • 4,341
  • 2
  • 14
  • 31