posted on Wednesday, January 21, 2004 8:22 PM by demiliani

Descriptions for the Enum Types

In your programs, you can use very often (for comfort) the Enum Type, and sometimes you would associate a description to the elements, for use it on the user interface.

A way to do this is to use the System.ComponentModel.Description attribute:

Public Enum Prove As Integer
         <System.ComponentModel.Description("Prova uno")> _
         Uno
         <System.ComponentModel.Description("Prova due")> _
         Due
         <System.ComponentModel.Description("Prova tre")> _
         Tre
End Enum

To retrieve these descriptions you can use the reflection:

Dim fields() As System.Reflection.FieldInfo
fields = GetType(Prove).GetFields(Reflection.BindingFlags.Public Or _
                                                      Reflection.BindingFlags.Static)

For Each field As System.Reflection.FieldInfo In fields
       Dim descriptions() As Object
       descriptions = field.GetCustomAttributes( _
                             GetType(System.ComponentModel.DescriptionAttribute), _
                              False)

       If descriptions.Length > 0 Then
              MsgBox(DirectCast(descriptions(0), _
                            System.ComponentModel.DescriptionAttribute).Description)
       End If

Next

Comments