C# – How to use enum

Enum is value type containing a set of constants representing associated integers. These integers can be assigned automatically, starting from 0 and incremented by 1 on consecutive items, or assigned directly by programmer. This article presents the way of implementing our own enum and also examples of its usage.

Enumeration type can be defined by enum keyword followed by its name. Below example creates an enum called Month representing every month of the year. There are no custom integers assigned to the items, so they’re generated implicitly. As a result of what January represents 0, February is 1, March is 2 and so on.

Let’s create two variables representing enum, which we’ve just created. First value is set using constant name January, and second one is integer “11” cast to Month type.

Both variables are printed to the console, in two different ways: by converting to string and to integer. As you can see casting enum type to string displays its constant text value, whilst casting to integer displays its allocated figure.

January is first element of our enumeration, and by default it represents integer “0”. Let’s consider a case, we’d like our enum to start with “1”. We can achieve it by defining integers ourselves.

After implementing above modification let’s create two objects again and print the values. This time variable m1, still represents January string, but its allocated integer is 1, whilst second variable m2 still represents integer 11 but text constant is November.