Enums
An enum is a special value type that lets you specify a group of named numeric constants. For example:
public enum BorderSide { Left, Right, Top, Bottom }
We can use this enum type as follows:
BorderSide topSide = BorderSide.Top; bool isTop = (topSide == BorderSide.Top); // true
Each enum member has an underlying integral value. By default, the
underlying values are of type int
, and
the enum members are assigned the constants 0
, 1
,
2
... (in their declaration order). You
may specify an alternative integral type, as follows:
public enum BorderSide : byte
{ Left, Right, Top, Bottom }
You may also specify an explicit integral value for each member:
public enum BorderSide : byte { Left=1
, Right=2
, Top=10
, Bottom=11
}
The compiler also lets you explicitly assign some of the enum members. The unassigned enum members keep incrementing from the last explicit value. The preceding example is equivalent to:
public enum BorderSide : byte { Left=1, Right, Top=10, Bottom }
Enum Conversions
You can convert an enum
instance to and from its underlying integral value with an explicit
cast:
int i = (int) BorderSide.Left; BorderSide side = (BorderSide) i; bool leftOrRight = (int) side <= 2;
You can also explicitly cast one enum type to another; the translation then uses the members’ underlying integral values.
The numeric literal 0
is
treated specially in that it does not require an explicit cast:
BorderSide b = 0; // No cast required if (b == 0) ...
In this particular example, BorderSide
has no member with an ...
Get C# 4.0 Pocket Reference, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.