Answers for "C# get enum value by DescriptionAttribute"

C#
0

C# get enum value by DescriptionAttribute

public static class EnumEx
{
    public static T GetValueFromDescription<T>(string description) where T : Enum
    {
        foreach(var field in typeof(T).GetFields())
        {
            if (Attribute.GetCustomAttribute(field,
            typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
            {
                if (attribute.Description == description)
                    return (T)field.GetValue(null);
            }
            else
            {
                if (field.Name == description)
                    return (T)field.GetValue(null);
            }
        }

        throw new ArgumentException("Not found.", nameof(description));
        // Or return default(T);
    }
}
var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");
Posted by: Guest on July-09-2021

C# Answers by Framework

Browse Popular Code Answers by Language