Tina Chen
Tina Chen

Reputation: 939

How to get enum value, string, and description

I am trying to loop through my enum and extract the value, string, and description out of it? How can I do this?

Enum Fruits
        <Description("$1.99/lb")> Apple = 1
        <Description("$0.99/lb")> Banana= 2
        <Description("$3.99/lb")> Orange= 3
End Enum

Persudo code

For Each item in Fruits
   Dim value as integer
   Dim text as string 
   Dim description as string
   Dim returnText = String.Format("ID: {0}  {1} is {2}", value, text, description) 
Next 

I will like to get:

ID: 1 Apple is $1.99/lb

ID: 2 Banana is $0.99/lb

ID: 3 Orange is $3.99/lb

Thank you for your help.

Upvotes: 1

Views: 6613

Answers (1)

That is a really bad way to manage data elements: every time the price of bananas goes up you have to change the code. Descriptions should be reserved for static items. Ex:

Friend Enum ImgSizes
     <Description("Large,  1600x900")> Lg = 1600               
     <Description("Medium, 1280x720")> Med = 1280
     <Description("Small,   720x480")> Sm = 720
End Enum

Here, the Description might be fetched for display in a combobox to provide a friendly translation. Otherwise, the value is just the integer value of the enum, and the name can be gotten from .ToString. The only trick is the description:

Shared Function GetDescription(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

Your loop needs work and you need to use OPTION STRICT. Loop thru the values to get the info you want. The index variable must As Fruits otehrwise it is not a Enum/Friuts, but an integer or object and nothing will work.

For Each v As Fruit In [Enum].GetValues(GetType(Fruits))
    returnText = String.Format("ID: {0}  {1} is {2}", 
          Convert.ToInt32(v), v.ToString, 
          GetDescription(GetType(v)) 
Next 

Upvotes: 1

Related Questions