2

Is it possible to return a value from enum with a string index? For example I can use:

Enum test
    firstval
    secondval
    thirdval
End Enum

Dim index As Integer = 1

CType(index, test).ToString()

to return firstval but is there a way to do something similar where index is a string value? For example:

Enum test
    firstval = "one"
    secondval = "two"
    thirdval = "three"
End Enum

Dim index As string = "one"

CType(index, test).ToString()
2
  • First of all, you can't set Enum as string: The Enum statement can declare the data type of an enumeration. Each member takes the enumeration's data type. You can specify Byte, Integer, Long, SByte, Short, UInteger, ULong, or UShort. Commented Sep 18, 2013 at 8:38
  • Use Dictionary<string,string> instead. Commented Sep 18, 2013 at 8:48

2 Answers 2

3

It's not possible using an Enum, but you could easily create a type that can do what you want, using the Narrowing operator.

simple example:

Class Test

    Private Shared _lookup As Dictionary(Of String, Test)

    Private Key As String
    Private Name As String

    Public Shared ReadOnly firstval  As Test = New Test("one", "firstval")
    Public Shared ReadOnly secondval As Test = New Test("two", "secondval")
    Public Shared ReadOnly thirdval  As Test = New Test("three", "thirdval")

    Private Sub New(key As String, name As String)
        Me.Key = key
        Me.Name = name
        If _lookup Is Nothing Then _
            _lookup = New Dictionary(Of String, Test)

        _lookup.Add(key, Me)
    End Sub

    Public Overrides Function ToString() As String
        Return Me.Name ' or whatever you want '
    End Function

    Public Shared Widening Operator CType(obj As Test) As String 
        Return obj.Key
    End Operator 

    Public Shared Narrowing Operator CType(key As String) As Test
        Return _lookup(key)
    End Operator 

End Class

usage:

Dim index As string = "one"

' returns firstval '
CType(index, Test).ToString() 
Sign up to request clarification or add additional context in comments.

2 Comments

Wow that looks great! I'm not sure I understand exactly what is going on with the widening and narrowing operators, do you know of any references for that? I tried googling but I didn't come up with much!
1

There are several other alternatives.

One is to get the names used in the enum. For instance:

Friend Enum ImgFormat
    Bitmap
    GIF
    JPeg
    TIFF
    PNG
End Enum

Dim ImgNames() As String
...
ImgNames = [Enum].GetNames(GetType(ImgFormat))

If your names are not friendly enough, decorate them with Descriptions:

Imports System.ComponentModel

Friend Enum ImgFormat
    <Description("Bitmap (BMP)")> Bitmap
    <Description("Graphic Interchange (GIF)")> GIF
    <Description("Jpg/JPeg (JPG)")> JPeg
    <Description("Tagged Image (TIFF)")> TIFF
    <Description("Portable Graphics (PNG)")> PNG
End Enum

To get the descriptions, requires reflection which gets involved:

Imports System.Reflection
Imports System.ComponentModel

Public Class EnumConverter
' gets a single enum description
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

' get all the enum descriptions:
Public Shared Function GetEnumDescriptions(ByVal type As Type) As String()
    Dim n As Integer = 0

    Dim enumValues As Array = [Enum].GetValues(type)
    Dim Descr(enumValues.Length - 1) As String

    For Each value As [Enum] In enumValues
         Descr(n) = GetEnumDescription(value)
         n += 1
    Next

    Return Descr

End Function
End Class

To use:

Dim ImgNames() As String = EnumConverter.GetEnumDescriptions(ImgFormat)

ImgNames(ImgFormat.GIF) would be 'Graphic Interchange (GIF)'

This will break if the Enum values are not the default 0, 1, 2 ... IF that is an issue (and it really is), then build a class around it to store the Name or Description with the Enum Value. Rather than building a class to create a pseudo enum, make one to create a list of name-value pairs consisting of the Descriptions and Enum Value.

2 Comments

Thanks, how would I go about getting the description using the enum value?
Use the EnumConverter class (shown) to get the Description to an array, then a given Enum value (when default vals 0123...) is also an index into the array for that description (as shown). If x is ImgFormat.GIF then ImgNames(x) would be 'Graphic Interchange (GIF)'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.