Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the description from an enum in VB.NET? [duplicate]

I have Enum as below

Public Enum FailureMessages
  <Description("Failed by bending")>
  FailedCode1 = 0

  <Description("Failed by shear force")>
  FailedCode2 = 1
End Enum

Each enum has its own description. For example, FailedCode1 has its own description as "Failed by bending".

Below is my main Sub() where I would like to assign a variable (type string) to the corresponding enum.

 Sub Main()
  Dim a As Integer = FailureMessages.FailedCode1
  Dim b As String 'I would b = Conresponding description of variable a above
  'that means: I would b will be "Failed by bending". How could I do that in .NET ?
 End Sub 

Can anyone please help me, how could I do that in VB.NET

like image 611
N.T.C Avatar asked Aug 25 '14 00:08

N.T.C


1 Answers

You need to use Reflection to retrieve the Description. Since these are user-added and therefore one or more could be missing, I like to have it return the Nameif the Attribute is missing.

Imports System.Reflection
Imports System.ComponentModel

Public Shared Function GetEnumDescription(e As [Enum]) As String

    Dim t As Type = e.GetType()

    Dim attr = CType(t.
                    GetField([Enum].GetName(t, e)).
                    GetCustomAttribute(GetType(DescriptionAttribute)), 
                    DescriptionAttribute)

    If attr IsNot Nothing Then
        Return attr.Description
    Else
        Return e.ToString
    End If

End Function

Usage:

Dim var As FailureMessages = FailureMessages.FailedCode1
Dim txt As String = GetDescription(var)

You can create a version to get all the Descriptions for an Enum:

Friend Shared Function GetEnumDescriptions(Of EType)() As String()
    Dim n As Integer = 0

    ' get values to poll
    Dim enumValues As Array = [Enum].GetValues(GetType(EType))
    ' storage for the result
    Dim Descr(enumValues.Length - 1) As String
    ' get description or text for each value
    For Each value As [Enum] In enumValues
        Descr(n) = GetEnumDescription(value)
        n += 1
    Next

    Return Descr
End Function

Usage:

Dim descr = Utils.GetDescriptions(Of FailureMessages)()
ComboBox1.Items.AddRange(descr)

Of T makes it a little easier to use. Passing the type would be:

Shared Function GetEnumDescriptions(e As Type) As String()
' usage:
Dim items = Utils.GetEnumDescriptions(GetType(FailureMessages))

Note that populating a combo with the names means you need to parse the result to get the value. Instead, I find it better/easier to put all the names and values into a List(Of NameValuePairs) to keep them together.

You can bind the control to the list and use DisplayMember to show the name to the user, while the code uses ValueMember to get back the actual typed value.

like image 147
Ňɏssa Pøngjǣrdenlarp Avatar answered Sep 20 '22 13:09

Ňɏssa Pøngjǣrdenlarp