Posted By

dimitrisdapontes on 01/26/13


enum description

Versions (?)

Who likes this?

1 person have marked this snippet as a favorite


Enum Description

 / Published in: VB.NET

Returns the description set in an enum value, or if no description is found it returns the name of the enum value. Use this without worrying about passing the enum type, you should only pass the enum value


Friend Enum Duration
    <Description("Every 12 Months")> Year = 1
    <Description("Every 6 Months")> Semester = 2
End Enum

GetEnumDescription(Duration.Year) returns "Every 12 Months"
  1. Imports System.Reflection
  2. Imports System.ComponentModel
  4. ''' <summary>
  5. ''' Returns the enum description (if any), otherwise returns the name of the enum value
  6. ''' </summary>
  7. Friend Shared Function GetEnumDescription(Of TEnum)(enumObj As TEnum) As String
  8. Dim fi As FieldInfo = enumObj.GetType().GetField(enumObj.ToString())
  10. Dim attributes As DescriptionAttribute() = fi.GetCustomAttributes(GetType(DescriptionAttribute), False)
  12. If attributes IsNot Nothing AndAlso attributes.Length > 0 Then
  13. Return attributes(0).Description
  14. Else
  15. Return enumObj.ToString()
  16. End If
  17. End Function

Report this snippet  

You need to login to post a comment.