Information Technology Reference
In-Depth Information
Setting the Underlying Type
To explicitly set the type associated with an enum, place a colon and the type name after the
enum name. The type can be any integral type except
char
. All the member constants are of
the enum's underlying type.
Colon
↓
enum TrafficLight : ulong
{
↑
...
Underlying type
Setting Explicit Values for the Members
The values of the member constants can be any values of the underlying type. To explicitly set
the value of a member, use an initializer after its name in the enum declaration. There can be
duplicate values, although not duplicate names, as shown here:
enum TrafficLight
{
Green = 10,
Yellow = 15, // Duplicate values
Red = 15 // Duplicate values
}
For example, when enum
TrafficLight
was declared in the preceding code, the compiler
defaults for the underlying type and numbering of the members were accepted. Now that you
know how to set these factors, you can create a declaration explicitly setting both characteris-
tics. Figure 13-2 shows the declarations.
The code on the left accepts the default type and numbering.
The code on the right explicitly sets the underlying type to
int
and the members to val-
ues corresponding to the default values.
Figure 13-2.
Equivalent enum declarations