In this post I will show how to read a description attribute of an enum value by reflection. Let us assume we have a enum like that .
public enum TestEnum
{
[Description("Select")]
NotAssigned,
[Description("First Test Pass")]
FirstTestPass,
[Description("Second Test Pass ")]
SecondTestpass
}
The code above, basically takes in the enumeration, uses Reflection to find the "DescriptionAttribute" on the member, and then returns the Description. If the DescriptionAttribute is not present on the enum, then we just call a ToString() on the enum to get the name.
public static string GetEnumDescription(Enum value)
{
AppLogger.Instance.Info();
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi?.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes?.Length > 0)
return attributes[0].Description;
return value.ToString();
}
So if call my above function like that .
var getEnumDescripation =
GetEnumDescription(
"1");
Input Enum Value ="1";
Out Put ="First Test Pass";
No comments:
Post a Comment