User-450085702 posted
Hi,
I have an enum with not-so-friendly names, so wanted to use [Description("friendly name")] on few of the enum constants. For example, I have the below enum, when I show it to user they should be Created, Order Processing, Processed instead of Created, Processing,
and Processed.
public enum OrderStatus {
Created,
[Description("Order Processing")] Processing,
Processed
}
I have written this extension method that can be invoked on enum constant to get the friendly name from Description attribute.
public static string GetDescription(this Enum enumValue)
{
var type = enumValue.GetType();
var memberInfo = type.GetMember(enumValue.ToString());
if (memberInfo.Length > 0)
{
var attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs.Length > 0) return ((DescriptionAttribute)attrs[0]).Description;
}
return null;
}
This method works great if my call is made like this: OrderStatus.Processing.GetDescription(). But because I have tons of Enums that I render on form, I am using Reflection to make this call at runtime. Let's say I am rendering this as a dropdown on
the form and the property looks like the following.
[Field(Type = FieldType.Select, EnumType = typeof(OrderStatus))]
public OrderStatus? OrderStatus
To provide the options in the Order Status dropdown, I am currently using Enum.GetNames(fieldAttribute.EnumType) but this doesn't consider the Description Attribute.
Question: How do I invoke .GetDescription extention method using EnumType and EnumName? I tried something like (fieldAttribute.EnumType)Enum.Parse(fieldAttribute.EnumType, EnumName).GetDescription() but type casting doesn't work this way.
Thank you in advance for looking into this and trying to help.
Regards,
Siva