Enums in C#

An enum type is a distinct value type with a set of named constants. The following example declares and uses  an enum type named Color with three constant values, Red, Green, and Blue.

Code Snippet
  1. using System;
  2. enum Color
  3. {
  4.     Red,
  5.     Green,
  6.     Blue
  7. }
  8. class Test
  9. {
  10.     static void PrintColor(Color color)
  11.     {
  12.         switch (color)
  13.         {
  14.             case Color.Red:
  15.                 Console.WriteLine("Red");
  16.                 break;
  17.             case Color.Green:
  18.                 Console.WriteLine("Green");
  19.                 break;
  20.             case Color.Blue:
  21.                 Console.WriteLine("Blue");
  22.                 break;
  23.             default:
  24.                 Console.WriteLine("Unknown color");
  25.                 break;
  26.         }
  27.     }
  28.     static void Main()
  29.     {
  30.         Color c = Color.Red;
  31.         PrintColor(c);
  32.         PrintColor(Color.Blue);
  33.     }
  34. }

Each enum type has a corresponding integral type called the underlying type of the enum type. An enum type that does not explicitly declare an underlying type has an underlying type of int. An enum type’s storage format and range of possible values are determined by its underlying type. The set of values that an enum type can take on is not limited by its enum members. In particular, any value of the underlying type of an enum can be cast to the enum type and is a distinct valid value of that enum type.
The following example declares an enum type named Alignment with an underlying type of sbyte.

Code Snippet
  1. enum Alignment : sbyte
  2. {
  3.     Left = -1,
  4.     Center = 0,
  5.     Right = 1
  6. }

As shown by the previous example, an enum member declaration can include a constant  expression that specifies the value of the member. The constant value for each enum member must be in the range of the underlying type of the enum. When an enum member declaration does not explicitly specify a value, the member is given the value zero (if it is  the first member in the enum type) or the value of the textually  preceding enum member plus one.
Enum values can be converted to integral values and vice versa using type casts. For example:

Code Snippet
  1. int i = (int)Color.Blue;            // int i = 2;
  2. Color c = (Color)2;                 // Color c = Color.Blue;

The default value of any enum type is the integral value zero converted to the enum type. In cases where variables are automatically initialized to a default value, this is the value given to variables of enum types. For the default value of an enum type to be easily available, the literal 0 implicitly converts to any enum type. Thus the following is permitted.

Color c = 0;

Post a Comment