Information Technology Reference
In-Depth Information
Underlying Types and Values
Every enum type has an underlying integral type. By default, the underlying type is
int
.
Each enum member is assigned a constant value of the underlying type.
Unless a member is initialized at its declaration, the compiler assigns each member a
value, starting with 0, and incrementing by 1.
For example, in the enum type
TrafficLight
declared previously, the compiler performed
the default actions, including setting the underlying type to
int
, and assigning the
int
values
0
,
1
, and
2
to members
Green
,
Yellow
, and
Red
, respectively. In the output of the following code,
you can see the underlying member values by casting them to type
int
. Their arrangement on
the stack is illustrated in Figure 13-1.
TrafficLight t1 = TrafficLight.Green;
TrafficLight t2 = TrafficLight.Yellow;
TrafficLight t3 = TrafficLight.Red;
Console.WriteLine("{0},\t{1}", t1, (int) t1);
Console.WriteLine("{0},\t{1}", t2, (int) t2);
Console.WriteLine("{0},\t{1}\n", t3, (
int)
t3);
↑
Cast to int
This code produces the following output:
Green, 0
Yellow, 1
Red, 2
Figure 13-1.
The member constants of an enum are represented by underlying integral values.