Me Myself & C#

Manoj Garg’s Tech Bytes – What I learned Today

Posts Tagged ‘Enum’

Reading Description of Enum values using Reflection in .Net 2.0

Posted by Manoj Garg on August 7, 2008

Suppose we have a situation where we want to bind an DropDown List with the values from an Enum. But we want to show different text for each enum member. for example we have following enum containing various actions a user can perform in a source control tool like check in, check out etc.

   1: public enum Actions
   2:     {
   3:         [Description("Check in")]
   4:         Checkin,
   5:         [Description("Check out")]
   6:         Checkout,
   7:         [Description("Undo Check out")]
   8:         UndoCheckOut,
   9:         [Description("View File")]
  10:         ViewFile,
  11:     }

Now on our page we want to show the text specified in Description attribute and the actual enum member name as its value. Following is an elegant way to do it in DotNet 2.0 using reflection.

   1: class ActionItems
   2: {
   3:     public string Text;
   4:     public string Value;
   5:
   6:     public ActionItems(string _text, string _value)
   7:     {
   8:         Text = _text;
   9:         Value = _value;
  10:     }
  11: }
  12:
  13: public List<ActionItems> GetActionListItems(Type EnumType)
  14: {
  15:     List<ActionItems> items = new List<ActionItems>();
  16:     foreach (string value in Enum.GetNames(EnumType))
  17:     {
  18:         /// Get field info
  19:         FieldInfo fi = EnumType.GetField(value);
  20:
  21:         /// Get description attribute
  22:         object[] descriptionAttrs = fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
  23:         DescriptionAttribute description = (DescriptionAttribute)descriptionAttrs[0];
  24:
  25:         ActionItems item = new ActionItems(description.Description, value);
  26:         items.Add(item);
  27:     }
  28:     return items;
  29: }

The method above GetActionListItems returns a list of type ActionItems which contains two fields Text and Value. This method uses Enum.GetNames method to get all the members in a given enum type. GetField method of type is used to get the information about that member. This method return an object of type FieldInfo. Using this FieldInfo object we can get the values of various custom attributes defined for that enum using GetCustomAttributes method.

   1: List<ActionItems> comboItems = GetActionListItems(typeof(Actions));

The above code can be used to call GetActionListItems method.

Hope it helps.

Ha-P Coding 🙂

Advertisements

Posted in C# | Tagged: , , | 5 Comments »