I have an enum like this (in C#)
public enum Cars
{
Toyota = 'T',
Honda = 'H',
Ford= 'F'
}
And a variable for myCar in VB
Dim myCarValue As String = "H"
How can I check to see if myCarValue is one of the valid values in the Cars enum without comparing comparing against every value in the email? Is there a way to use Contains() to do this?
>Solution :
You can use only numeric types in Enums. This code does simply not compile. You will get the compiler error:
Conversion from ‘String’ to ‘integer’ cannot occur in a constant expression
You must choose a different approach. I suggest using constants and a HashSet(Of String) to store them:
Public Module Cars
Public Const Toyota = "T", Honda = "H", Ford = "F"
Private ReadOnly _values As HashSet(Of String) = New HashSet(Of String) From {
Toyota,
Honda,
Ford
}
Public Function IsValidValue(carCode As String) As Boolean
Return _values.Contains(carCode)
End Function
End Module
Now you can do a check like:
Dim myCarValue As String = "H"
If Cars.IsValidValue(myCarValue) Then
End If
You can also get a specific value with
Dim myCarValue As String = Cars.Toyota
This is very much how you would do it with an Enum.
If the values always consists of a single character, you could also declare the Enum as:
Enum Cars
Totota = Asc("X")
Honda = Asc("H")
Fors = Asc("F")
End Enum
But then the check gets a bit ugly:
If System.Enum.IsDefined(Of Cars)(Asc(myCarValue)) Then
End If
Note that in C# single quotes denote the System.Char type (C#: char, VB: Char) which is considered to be a 16-bit numeric type (like System.Short) and is implicitly converted to an Integer in C#.