When you declare an enum you actually create a new type. However every enum type has an underlying integral data type (sbyte, byte, short, ushort, int, uint, long, ulong). If no explicit type is specifed the default is “int”. So any enum value can be casted into it’s underlying type and back:
public enum MyEnum : int
{
A, B, C, D
}
// ...
MyEnum someEnumValue;
someEnumValue = MyEnum.B;
int val = (int)someEnumValue; // val == 1
someEnumValue = (MyEnum)2; // someEnumValue == "C"
Note that an enum value literally is the same as it’s underlying value. You can even assign an integer value to an enum that doesn’t have a corresponding “constant”:
someEnumValue = (MyEnum)42; // no constant inside MyEnum for this value 42
A common way if you want a countable enum is to define a special “Count” or “Size” value as last element:
public enum Mode
{
M1, // == 0
M2, // == 1
M3, // == 2
M4, // == 3
Count // == 4
}
public Mode mode;
This way one can simply do:
mode++;
if (mode >= Mode.Count)
mode = Mode.M1;
This would increase the value by one each time and checks if we reached our additional “Count” value if so go back to the first. That way you have a cycle. M1 → M2 .> M3 → M4 → M1 → M2 → …
Note that this of course only works as long as your enum values are sequencial. Enum values can be specified however you like:
public MyEnum
{
A = 45,
B = 545,
D = 65536,
chicken = 1
}