Results 1 to 7 of 7

Thread: [.NET 2.0+] Displaying Friendly Names for Enumerations

Threaded View

  1. #1

    Thread Starter
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    [.NET 2.0+] Displaying Friendly Names for Enumerations

    C# version here.

    I've seen information on this technique in several places, possibly even on this forum. I've extended what I've read by creating a couple of classes that make displaying friendly names easier.

    First, a bit of background. Enumerations, created in VB with the Enum key word, are lists of text values that each correspond to a number. They are used to provide a limited list of possible values. We use them in many situations, for instance the DialogResult values that are returned by MessageBox.Show are members of the DialogResult enumeration. The idea is that the text labels are descriptive and make life easier for the developer, while the system uses the underlying numeric values for speed and efficiency. Enumerations are better than either String or Integer when you want to limit the possible choices a variable can take.

    I say that the text labels are friendly to the developer, but what about the user? The text labels used for enumerated constants must obey the same rules as other identifiers. That means that they must start with a letter or an underscore and can only contain letters, numbers and underscores. They cannot contain spaces or punctuation. That makes them a little less friendly to display to the user in the UI. It would be nice if we could associate a standard String with each value and display those to the user. Well, we can do that, using the DescriptionAttribute class:
    vb.net Code:
    1. Imports System.ComponentModel
    2.  
    3. Public Enum TestEnum
    4.     <Description("This is the first value")> FirstValue
    5.     <Description("Hello from the second value")> SecondValue
    6.     <Description("Third value here")> ThirdValue
    7. End Enum
    Note the spaces in the descriptions that are not allowed in the value names themselves. Now, the question is, how do we actually get those descriptions in code? The answer is to use reflection. In other places I've seen this done with a method at the form level or the like. I've been a good little OOPer and created a couple of classes to do the job. The following EnumDescriptor class encapsulates the reflection code, providing access to an enumerated value and its description via properties:
    vb.net Code:
    1. Imports System.ComponentModel
    2. Imports System.Reflection
    3.  
    4. ''' <summary>
    5. ''' Contains an enumerated constant value and a friendly description of that value, if one exists.
    6. ''' </summary>
    7. ''' <typeparam name="T">
    8. ''' The enumerated type of the value.
    9. ''' </typeparam>
    10. Public Class EnumDescriptor(Of T)
    11.  
    12.     ''' <summary>
    13.     ''' The friendly description of the value.
    14.     ''' </summary>
    15.     Private _description As String
    16.     ''' <summary>
    17.     ''' The enumerated constant value.
    18.     ''' </summary>
    19.     Private _value As T
    20.  
    21.     ''' <summary>
    22.     ''' Gets the friendly description of the value.
    23.     ''' </summary>
    24.     ''' <value>
    25.     ''' A <b>String</b> containing the value's Description attribute value if one exists; otherwise, the value name.
    26.     ''' </value>
    27.     Public ReadOnly Property Description() As String
    28.         Get
    29.             Return Me._description
    30.         End Get
    31.     End Property
    32.  
    33.     ''' <summary>
    34.     ''' Gets the enumerated constant value.
    35.     ''' </summary>
    36.     ''' <value>
    37.     ''' An enumerated constant of the <b>EnumDescriptor's</b> generic parameter type.
    38.     ''' </value>
    39.     Public ReadOnly Property Value() As T
    40.         Get
    41.             Return Me._value
    42.         End Get
    43.     End Property
    44.  
    45.     ''' <summary>
    46.     ''' Creates a new instance of the <b>EnumDescriptor</b> class.
    47.     ''' </summary>
    48.     ''' <param name="value">
    49.     ''' The value to provide a description for.
    50.     ''' </param>
    51.     Public Sub New(ByVal value As T)
    52.         Me._value = value
    53.  
    54.         'Get the Description attribute.
    55.         Dim field As FieldInfo = value.GetType().GetField(value.ToString())
    56.         Dim attributes As DescriptionAttribute() = DirectCast(field.GetCustomAttributes(GetType(DescriptionAttribute), _
    57.                                                                                         False),  _
    58.                                                               DescriptionAttribute())
    59.  
    60.         'Use the Description attribte if one exists, otherwise use the value itself as the description.
    61.         Me._description = If(attributes.Length = 0, _
    62.                              value.ToString(), _
    63.                              attributes(0).Description)
    64.     End Sub
    65.  
    66.     ''' <summary>
    67.     ''' Overridden.  Creates a string representation of the object.
    68.     ''' </summary>
    69.     ''' <returns>
    70.     ''' The friendly description of the value.
    71.     ''' </returns>
    72.     Public Overrides Function ToString() As String
    73.         Return Me.Description
    74.     End Function
    75.  
    76. End Class
    I've also created a class to automatically create an EnumDescriptor for each member of an enumeration and store them as a collection:
    vb.net Code:
    1. ''' <summary>
    2. ''' A collection of EnumDescriptors for an enumerated type.
    3. ''' </summary>
    4. ''' <typeparam name="T">
    5. ''' The type of the enumeration for which the EnumDescriptors are created.
    6. ''' </typeparam>
    7. Public Class EnumDescriptorCollection(Of T)
    8.     Inherits ObjectModel.Collection(Of EnumDescriptor(Of T))
    9.  
    10.     ''' <summary>
    11.     ''' Creates a new instance of the <b>EnumDescriptorCollection</b> class.
    12.     ''' </summary>
    13.     Public Sub New()
    14.         'Populate the collection with an EnumDescriptor for each enumerated value.
    15.         For Each value As T In [Enum].GetValues(GetType(T))
    16.             Me.Items.Add(New EnumDescriptor(Of T)(value))
    17.         Next
    18.     End Sub
    19.  
    20. End Class
    An example of how you might use these classes is:
    vb.net Code:
    1. Public Class Form1
    2.  
    3.     Private Sub Form1_Load(ByVal sender As Object, _
    4.                            ByVal e As EventArgs) Handles MyBase.Load
    5.         Me.ComboBox1.DisplayMember = "Description"
    6.         Me.ComboBox1.ValueMember = "Value"
    7.         Me.ComboBox1.DataSource = New EnumDescriptorCollection(Of TestEnum)
    8.     End Sub
    9.  
    10.     Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, _
    11.                                                ByVal e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    12.         MessageBox.Show(Me.ComboBox1.SelectedValue.ToString(), Me.ComboBox1.Text)
    13.     End Sub
    14.  
    15. End Class
    So, there's no need for you to mess around each time you want to do this once you have these classes. It's one line to create a collection containing the enumerated values and their descriptions, which you can bind or use however you like.

    I've attached code files for the EnumDescriptor and EnumDescriptorCollection classes.
    Attached Files Attached Files
    Last edited by jmcilhinney; Jan 6th, 2009 at 01:57 AM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width