© Mikael Olsson 2020
M. OlssonC# 8 Quick Syntax Referencehttps://doi.org/10.1007/978-1-4842-5577-3_20

20. Enum

Mikael Olsson1 
(1)
HAMMARLAND, Finland
 
An enumeration is a special kind of value type consisting of a list of named constants. To create one, you use the enum keyword followed by a name and a code block containing a comma-separated list of constant elements.
enum State { Run, Wait, Stop };
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;
}

Enum Constant Values

There is usually no need to know the actual constant values that the enum constants represent, but sometimes it can be useful. 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
};
These default values can be overridden by assigning values to the constants. The values can be computed from an expression and they do not have to be unique.
enum State
{
  Run = 0, Wait = 3, Stop = Wait + 1
};

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 any 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.
static void Main()
{
  State s = State.Run;
  int i = (int)s; // 0
  string t = s.ToString(); // Run
}
Several enumeration methods are available in the System.Enum class, such as GetNames() to obtain an array containing the names of the enum constants. Note that this method takes a type object (System.Type) as its argument, which is retrieved using the typeof operator .
enum Colors { Red, Green };
static void Main()
{
  foreach (string s in System.Enum.GetNames(typeof(Colors)))
  {
    System.Console.Write(s); // "RedGreen"
  }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.165.247