Enums in Visual Basic .NET
Our enum type ServerState has an underlying int type.
The possible values for ServerState are defined as constants. The special feature Enum generates successive constant values automatically; in this case 0, 1, 2 and so on.
By implementing the ToString method, values of ServerState can be printed out or converted to strings.
If we have a value of type Integer, we cannot pass it to Transition - the compiler will complain about type mismatch. This provides some degree of compile-time type safety for enums.
Transition emulates a state transition for a server; it takes the existing state and returns a new state.
Module Enums
Enum ServerState
StateIdle = 0
StateConnected
StateError
StateRetrying
End Enum
Dim stateName As New Dictionary(Of ServerState, String) From {
{ServerState.StateIdle, "idle"},
{ServerState.StateConnected, "connected"},
{ServerState.StateError, "error"},
{ServerState.StateRetrying, "retrying"}
}
Function ServerStateToString(ByVal ss As ServerState) As String
Return stateName(ss)
End Function
Sub Main()
Dim ns As ServerState = Transition(ServerState.StateIdle)
Console.WriteLine(ServerStateToString(ns))
Dim ns2 As ServerState = Transition(ns)
Console.WriteLine(ServerStateToString(ns2))
End Sub
Function Transition(ByVal s As ServerState) As ServerState
Select Case s
Case ServerState.StateIdle
Return ServerState.StateConnected
Case ServerState.StateConnected, ServerState.StateRetrying
' Suppose we check some predicates here to determine the next state...
Return ServerState.StateIdle
Case ServerState.StateError
Return ServerState.StateError
Case Else
Throw New ArgumentException("unknown state: " & s.ToString())
End Select
End Function
End ModuleTo run the program, put the code in Enums.vb and use vbc to compile it.
$ vbc Enums.vb
$ Enums.exe
connected
idleThis example illustrates the use of enums by creating a simple state transition mechanism for a server. By defining an enum type and using a Dictionary to map enum values to strings, we can easily print out meaningful representations of the states.