Enumerations

Enumerations provide a powerful alternative to constants. An enumeration is a distinct value type, consisting of a set of named constants (called the enumerator list).

Every enumeration has an underlying type, which can be any integral type (integer, short, long, etc.) except for char. The technical definition of an enumeration is:

[attributes] [modifiers] enum identifier

[:base-type] {enumerator-list};

An enumeration begins with the keyword enum, which is generally followed by an identifier, such as:

enum Temperatures

The base type is the underlying type for the enumeration. If you leave out this optional value (and
often you will) it defaults to integer, but you are free to use any of the integral types (e.g., ushort,
long) except for char. For example, the following fragment declares an enumeration of unsigned
integers (uint):
enum ServingSizes :uint
{
Small = 1,
Regular = 2,
Large = 3
}
Notice that an enum declaration ends with the enumerator list. The enumerator list contains the
constant assignments for the enumeration, each separated by a comma.

The base type is the underlying type for the enumeration. If you leave out this optional value (and often you will) it defaults to integer, but you are free to use any of the integral types (e.g., ushort, long) except for char. For example, the following fragment declares an enumeration of unsigned

integers (uint):
enum ServingSizes :uint
{
Small = 1,
Regular = 2,
Large = 3
}
Notice that an enum declaration ends with the enumerator list. The enumerator list contains the constant assignments for the enumeration, each separated by a comma.

Each constant in an enumeration corresponds to a numerical value an integer. If you don’t specifically set it otherwise, the enumeration begins at 0 and each subsequent value counts up from the previous.

If you create the following enumeration:

enum SomeValues

{

Programming C#

page 31

First,

Second,

Third = 20,

Fourth

}

the value of First will be 0, Second will be 1, Third will be 20, and Fourth will be 21. Enums are formal types; therefore an explicit conversion is required to convert between an enum type and an integral type.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: