Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get VB.net Enum Description from Value

Tags:

enums

vb.net

How can I get Enum description from its value?

I can get the description from the name using:

Public Shared Function GetEnumDescription(ByVal EnumConstant As [Enum]) As String
    Dim fi As FieldInfo = EnumConstant.GetType().GetField(EnumConstant.ToString())
    Dim attr() As DescriptionAttribute = _ 
                  DirectCast(fi.GetCustomAttributes(GetType(DescriptionAttribute), _
                  False), DescriptionAttribute())

    If attr.Length > 0 Then
        Return attr(0).Description
    Else
        Return EnumConstant.ToString()
    End If
End Function 

But I cant figure out how to pass a variable name to this function. I've tried things like

GetEnumDescription([Enum].GetName(GetType(myEnum), 2)))

but nothing I've tried is correct.

like image 971
doovers Avatar asked Sep 19 '13 07:09

doovers


2 Answers

If you have a variable of your enum type, it's simply

GetEnumDescription(myEnum)

Minimal working example:

Enum TestEnum
    <Description("Description of Value1")>
    Value1
End Enum

Public Sub Main()
    Dim myEnum As TestEnum = TestEnum.Value1
    Console.WriteLine(GetEnumDescription(myEnum)) ' prints "Description of Value1"
    Console.ReadLine()
End Sub

If you have an Integer variable, you need to cast it to your enum type first (CType works as well):

GetEnumDescription(DirectCast(myEnumValue, TestEnum))

Working example:

Enum TestEnum
    <Description("Description of Value1")>
    Value1 = 1
End Enum

Public Sub Main()
    Console.WriteLine(GetEnumDescription(DirectCast(1, TestEnum)))
    Console.ReadLine()
End Sub

The source for your confusion seems to be a misunderstanding: Your method does not take the "name" of an enum as a parameter, it takes an Enum as a parameter. That's something different, and it's also the reason why your attempts to use GetName failed.

like image 91
Heinzi Avatar answered Sep 22 '22 18:09

Heinzi


Here's another solution to get an Enum's description as an extension.

Imports System.ComponentModel
Imports System.Runtime.CompilerServices

<Extension()> Public Function GetEnumDescription(ByVal EnumConstant As [Enum]) As String
    Dim attr() As DescriptionAttribute = DirectCast(EnumConstant.GetType().GetField(EnumConstant.ToString()).GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())
    Return If(attr.Length > 0, attr(0).Description, EnumConstant.ToString)
End Function

Example use from the previous posts:

Enum Example
    <Description("Value1 description.")> Value1 = 1
    <Description("Value2 description.")> Value2 = 2
End Enum

Sub Main()
    Console.WriteLine(DirectCast(2, Example).GetEnumDescription())
    Console.ReadLine()
End Sub
like image 28
mikro Avatar answered Sep 19 '22 18:09

mikro