C Sharp Syntax - Types - Value Types - Enumerations

Enumerations

Enumerated types (enums) are named values representing integer values.

enum Season { Winter = 0, Spring = 1, Summer = 2, Autumn = 3, Fall = Autumn // Autumn is called Fall in American English. }

enum variables are initialized by default to zero. They can be assigned or initialized to the named values defined by the enumeration type.

Season season; season = Season.Spring;

enum type variables are integer values. Addition and subtraction between variables of the same type is allowed without any specific cast but multiplication and division is somewhat more risky and requires an explicit cast. Casts are also required for converting enum variables to and from integer types. However, the cast will not throw an exception if the value is not specified by the enum type definition.

season = (Season)2; // cast 2 to an enum-value of type Season. season = season + 1; // Adds 1 to the value. season = season + season2; // Adding the values of two enum variables. int value = (int)season; // Casting enum-value to integer value. season++; // Season.Spring (1) becomes Season.Summer (2). season--; // Season.Summer (2) becomes Season.Spring (1).

Values can be combined using the bitwise-OR operator .

Color myColors = Color.Green | Color.Yellow | Color.Blue;

See also

  • Enumeration (programming)

Read more about this topic:  C Sharp Syntax, Types, Value Types