Thursday 12 December 2019

C#.NET - Reflection - Get Enum Value from Description Attribute

Below snippet will get the Enum value by the Enum description
public T GetEnumValueFromDescription(string description)
{
    Type type = typeof(T);
    if (!type.IsEnum)
    {
        throw new ArgumentException();
    }

    FieldInfo[] fields = type.GetFields();
    var field = fields
                    .SelectMany(f => f.GetCustomAttributes(
                        typeof(DescriptionAttribute), false), (
                            f, a) => new { Field = f, Att = a })
                    .Where(a => ((DescriptionAttribute)a.Att)
                        .Description == description).SingleOrDefault();
    return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
}

No comments: