posted on Tuesday, January 25, 2005 7:45 AM
by
roydictus
Converting Integers to Enums
When working on a large application, I had to write some utility functions to convert integers into corresponding enum values. Say you had an enum like the following:
Public
Enum TrafficLight As Integer
None = 0
Red = 1
Yellow = 2
Green = 3
End Enum
Then you could have a function to convert integers to TrafficLights such as
Public Function TrafficLightFromInt32(value As Integer) As TrafficLight
At first, I tried solving it by using the following technique:
Public Function TrafficLightFromInt32(value As Integer) As TrafficLight
Dim result As TrafficLight
result = DirectCast(System.ComponentModel.TypeDescriptor.GetConverter(GetType(TrafficLight)).ConvertFrom(value), TrafficLight)
Return result
End Function
But that didn't work, because EnumConverter can't convert from a System.Int32.
The solution was in fact much simpler:
Private Function TrafficLightFromInteger(ByVal value As Integer) As TrafficLight
Dim name As String = [Enum].GetName(GetType(TrafficLight), value)
Dim result As TrafficLight = DirectCast([Enum].Parse(GetType(TrafficLight), name), TrafficLight)
Return result
End Function
And voilà...
Update: I am deeply humbled by the much simpler solutions that Wes and Wesner have offered in the Feedback to this posting. There's no need to parse and cast, a simple CType() -- in the case of Visual Basic.Net -- does the trick. I have an aversion for CType() but in this case it's totally unjustified. Thanks for pointing that out!
Update 2: However, there is a caveat to using CType(). That is, enums are by default stored as Integer. You can then CType any integer to the enum, even integers that don't represent legal values. To take the example above, you can do CType(5, TrafficLight) and it wouldn't even throw an exception at runtime. You can solve that by checking for valid enum values before using them, as in the following example:
Public Sub UpdateTrafficLight(value As TrafficLight)
If Not [Enum].IsDefined(GetType(TrafficLight), value ) Then
Throw New ArgumentException("UpdateTrafficLight: value is invalid.")
End If
...
End Sub