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 Attributes() As DescriptionAttribute = _
DirectCast( _
fi.GetCustomAttributes(GetType(DescriptionAttribute), False), _
DescriptionAttribute() _
)
If Attributes.Length > 0 Then
Return Attributes(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.
The names of enumeration constants can be extracted by either Enum.GetNames
or the enumeration members’ ToString
method: Enumeration format strings – Microsoft Docs.