What if we need to save the value of an instance of an enumeration (Enum) as string and then get back the value again?
For instance, we have the following code:
Dim eDay As System.DayOfWeek = DayOfWeek.Monday
So now we can get a textual representation of eDay using the built-in ToString() method:
MessageBox.Show(eDay.ToString())
This yields a messagebox saying “Monday”. But how do we do the reverse (i.e., we know only the string representation “Monday”, but we need the enum value)? The trivial approach would be:
Dim sStr As String = "Monday"
Dim eDay As System.DayOfWeek
Select Case sStr
Case "Monday" : eDay = DayOfWeek.Monday
Case "Tuesday" : eDay = DayOfWeek.Tuesday
'...
End Select
No, this sounds too dumb. We can use the built-in shared function Parse
of the System.Enum
class. Method accepts two parameters, the type of enumeration and the actual value being parsed.
eDay = System.Enum.Parse(GetType(System.DayOfWeek), "Monday")
This only works with option strict set to off, because Enum.Parse()
returns a System.Object
value. So when using option strict set to on, the code gets more obfuscated:
eDay = CType( _
System.Enum.Parse(GetType(System.DayOfWeek), "Monday"), _
System.DayOfWeek)
Anyway, now we have the value! :)