Enums in C#

Our enum type ServerState has an underlying int type.

enum ServerState
{
    StateIdle,
    StateConnected,
    StateError,
    StateRetrying
}

The possible values for ServerState are defined as constants. In C#, enum values are automatically assigned successive integer values starting from 0.

By implementing the ToString method, values of ServerState can be printed out or converted to strings.

using System;
using System.Collections.Generic;

enum ServerState
{
    StateIdle,
    StateConnected,
    StateError,
    StateRetrying
}

class Program
{
    static readonly Dictionary<ServerState, string> stateName = new Dictionary<ServerState, string>
    {
        { ServerState.StateIdle, "idle" },
        { ServerState.StateConnected, "connected" },
        { ServerState.StateError, "error" },
        { ServerState.StateRetrying, "retrying" }
    };

    static void Main()
    {
        var ns = Transition(ServerState.StateIdle);
        Console.WriteLine(ns);
        var ns2 = Transition(ns);
        Console.WriteLine(ns2);
    }

    static ServerState Transition(ServerState s)
    {
        switch (s)
        {
            case ServerState.StateIdle:
                return ServerState.StateConnected;
            case ServerState.StateConnected:
            case ServerState.StateRetrying:
                return ServerState.StateIdle;
            case ServerState.StateError:
                return ServerState.StateError;
            default:
                throw new Exception($"unknown state: {s}");
        }
    }
}

To run the program, compile the code with csc (C# Compiler) and run the executable.

$ csc Program.cs
$ Program.exe
connected
idle