1. Herfried K. Wagner’s VB.Any
  2. .NET
  3. Frequently Asked Questions

Adding descriptions to enumeration constants

Adding descriptions to enumeration constants
<URL:http://dotnet.mvps.org/dotnet/faqs/?id=enumdescription&lang=en>
----------------------------------------------------------------------------

Adding descriptions to enumeration constants

Descriptions for members of an enumeration can be added using an attribute:

\\\
Imports System.ComponentModel
Imports System.Reflection

Private Enum Weekdays
    <Description("Sunday.")> _
    Sun
    <Description("Monday.")> _
    Mon
    <Description("Tuesday.")> _
    Tue
    <Description("Wednesday.")> _
    Wed
    <Description("Thursday.")> _
    Thu
    <Description("Friday.")> _
    Fri
    <Description("Saturday.")> _
    Sat
End Enum

Private Function GetDescription(ByVal EnumConstant As [Enum]) As String
    Dim fi As FieldInfo = EnumConstant.GetType().GetField(EnumConstant.ToString())
    Dim aattr() As DescriptionAttribute = _
        DirectCast( _
            fi.GetCustomAttributes(GetType(DescriptionAttribute), False), _
            DescriptionAttribute() _
        )
    If aattr.Length > 0 Then
        Return aattr(0).Description
    Else
        Return EnumConstant.ToString()
    End If
End Function
///

Usage:

\\\
MsgBox(GetDescription(Weekdays.Wed))
///

Notice that this way to add a string representation of the enumeration
constants is inflexible and hard to localize.

Enumeration constants' names can be extracted by either 'Enum.GetNames' or
the enum's members' 'ToString' method:

.NET Framework Developer's Guide -- Enumeration Format Strings
<URL:http://msdn.microsoft.com/library/en-us/cpguide/html/cpconenumerationformatstrings.asp>