C# Enums – Handling Long Descriptive String Values – Using Reflection

Consider the following scenario, you have an Enum, for which you have ‘Description’ attributes as shown below

public enum Status
 [Description("Status is Incomplete")]
 Incomplete = 0,
 [Description("Status is Complete")]
 Complete = 1,
 [Description("Status is Reserved")]
 Reserved = 2,
 [Description("Stauts is Confirmed")]
 Confirmed = 3,
 [Description("Stauts is Cancelled")]
 Cancelled = 99

You want to display these values in a drop down, where the text field is same as the Enum’s ‘Description’ text and the drop down value field same as the Enum’s int value.

If you have one Enum with such requirements, you would probably hard code it (I know), but in real world applications, you would have nearly 30 to 40 Enums, used at more than one place in the application, hence hard coding to the drop down is not an option. Also, let suppose we have the project requirement that the drop down should update itself when Enum is updated.

In short, we want a dynamic drop down, whose source is Enum values and if we add/remove values to the Enum, the drop down will update it self.

How to go about this ?

Lets use .NET extension and reflection and try to achieve this

The following code will use return the ‘Description Attribute’ of any Type of source using reflection

public static string GetDescriptionAttr(this T source)
 FieldInfo fi = source.GetType().GetField(source.ToString());

 if (fi == null)
 return string.Empty;

 var attribute = (DescriptionAttribute) fi.GetCustomAttributes(typeof (DescriptionAttribute), false)[0];

 if (attribute == null)
 return string.Empty;

 return attribute.Description;

Once this code is in place, we could write a helper function which will convert Enums to ListItemCollection where ‘Description’ attribute is used as text and Enum’s int value is used as ‘value’ field for the drop down option.

 public static ListItemCollection EnumToList(Type enumType)
 var list = new ListItemCollection();

 foreach (var type in Enum.GetValues(enumType))
   list.Add(new ListItem(String.Format(" {0}", type.GetDescriptionAttr()), ((int)type).ToString()));

 return list;

And finally, in the code behind, you just need to pass in the Enum value to this helper method, which will use reflection and return the dynamic list for the drop down

MyDropDown.DataSource = EnumToList(typeof(Status));

Thanks !

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.