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.
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.
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.
The above code can be used to call GetActionListItems method.
Hope it helps.
Ha-P Coding 🙂