0

Say I have a console app with the following code:

Enum FoodItems

   apple
   banana
   pineapple

End Enum

Sub Main()

   Dim input As String = Console.ReadLine()

End Sub

I want to be able to get a value from a particular member in FoodItems if input has the same value as a name of a member from the enum; ie get 1 when input is "banana". How could this be done working off this code?

2 Answers2

0

I didn't know if I understood so well: you want the user to write something, if this something is a word in your Enum, the output will be the "number of the word in the Enum"? For example, if I write banana, the application will write 1. If this is what you want you can easily do it like this:

If input = FoodItems.banana.ToString() Then Console.WriteLine(FoodItems.banana)
    Console.ReadLine()

If you want to check for all the elements in the Enum you have to Select Case:

    Sub Main()
    Dim input As String = Console.ReadLine()
    Select Case input
        Case FoodItems.apple.ToString()
            Console.WriteLine(FoodItems.apple)
        Case FoodItems.banana.ToString()
            Console.WriteLine(FoodItems.banana)
        Case FoodItems.pineapple.ToString()
            Console.WriteLine(FoodItems.pineapple)
    End Select
    Console.ReadLine()
End Sub

Probably there is a better way to do it, but I would do it like this.

Johnson
  • 297
  • 2
  • 5
  • 18
0

You could try this - It worked fine for me. The function below either returns the enum index if the string is an enum, or returns -1 if not.

<Flags> Friend Enum test
    banana
    apple
    orange
    pear
End Enum

Private Function ReturnEnum(inputString As String) As Integer
    Dim a As test
    Try
        a = test.Parse(GetType(test), inputString)
    Catch
        Return -1
    End Try
    Return CInt(a)
End Function
David Wilson
  • 4,369
  • 3
  • 18
  • 31