News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

C# Tutorial – 21 – Enum

An enumeration is a special kind of value type consisting of a list of named constants. To create one, the enum keyword is used followed by a name and a code block, containing a comma-separated list of constant elements.

enum State 
{
  Run, Wait, Stop, Offline
};

This enumeration type can be used to create variables that can hold these constants. To assign a value to the enum variable, the elements are accessed from the enum as if they were static members of a class.

State s = State.Run;

Enum example

The switch statement provides a good example of when an enumeration can be useful. Compared to using ordinary constants, an enumeration has the advantage of allowing the programmer to clearly specify what constant values are allowed. This provides compile-time type safety, and IntelliSense also makes the values easier to remember.

switch (s)
{
  case State.Run:     break;
  case State.Wait:    break;
  case State.Stop:    break;
  case State.Offline: break;
}

Enum constant values

There is usually no need to know the actual constant values that the constants represent, but sometimes it may be necessary. By default, the first element has the value 0, and each successive element has one value higher.

enum State
{
  Run,    // 0
  Wait,   // 1
  Stop,   // 2
  Offline // 3
};

These default values can be overridden by assigning values to the constants. The values can be computed and do not have to be unique.

enum State
{
  Run = 0, Wait = 3, Stop = 5, Offline = Stop + 5
};

Enum constant type

The underlying type of the constant elements is implicitly specified as int, but this can be changed by using a colon after the enumeration’s name followed by the desired integer type.

enum MyEnum : byte {};

Enum access levels and scope

The access levels for enumerations are the same as for classes. They are internal by default, but can also be declared as public. Although enumerations are usually defined at the top-level, they may be contained within a class. In a class they have private access by default, and can be set to either one of the access levels.

Enum methods

An enumeration constant can be cast to an int and the ToString method can be used to obtain its name. Most other enumeration methods can be found in the System.Enum class.

static void Main()
{
  State s = State.Run;
  int i = (int)s; // 0
  string t = s.ToString(); // Run
}