enum

Summary

Declares an enumeration.

Syntax

enum name [: type] {
    member1[= value1 [, member2 [, member3 ... [, memberN]]]]
}

Parameters

name
The name of the enumeration. This can be any valid identifier.
type
The underlying type of the enumeration. Can be signed or unsigned byte, short, int, or long.
memberN
The name of the enum members.
valueN
The value to initialize the member to. All subsequent members will be an increment relative to this value.

Description

The enum keyword declares an enumeration. An enumeration consists of a list of sequential members. The values of an enumeration are a sequence beginning from zero (0).

Basics

1
enum DaysOfWeek { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

In the above enumeration, DaysOfWeek.SUNDAY is set to the default starting value, zero (0). DaysOfWeek.MONDAY is set to 1, DaysOfWeek.TUESDAY to 2, and so on.

Enumeration members can also be re-defined to a different value. Subsequent members of the enumeration will be an increment relative to this value. For example:

1
enum DaysOfWeek { SUNDAY = 1, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

In this case, DaysOfWeek starts at one (1). Therefore, DaysOfWeek.SUNDAY equals 1, DaysOfWeek.MONDAY equals 2, and so forth.

Multiple enumeration members can also be initialized:

1
enum DaysOfWeek { SUNDAY = 1, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY = 10, SATURDAY }

Once again, DaysOfWeek.SUNDAY equals 1, DaysOfWeek.MONDAY equals 2, and so forth until DaysOfWeek.FRIDAY. DaysOfWeek.FRIDAY is initialized to 10, and all subsequent members will be an increment of this value. Thus, DaysOfWeek.SATURDAY equals 11.

enum members can only be initialized to a numeric literal. The default underlying type of the enum is a 32-bit signed integer, and the numeric literal must fit within the specified type's range. More than one enum member can be initialized. The incrementing sequence will always continue from the value of the last initialized member.

Enumerations are preferred to raw numeric literals for readability. Consider the following code:

1
2
3
4
5
6
7
8
9
if (today == DaysOfWeek.MONDAY) {
    // ...
}
 
// versus...
 
if (today == 1) {
    // ...
}

In the Type System

Enumerations are incorporated into the type system. Enumerations allow us to write type-safe code and restrict values.

1
2
3
enum Importance { None, Regular, Critical }
 
Importance errorLevel = Importance.Critical;

Compilation

enum values are constant and cannot be changed. The compiler will directly compile the constant value whenever an enum member is referenced.

Implicit 'static'

Enumerations nested inside modules and classes are implicitly static.

Examples

Underlying enum type
1
enum DaysOfWeek : byte { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

See Also

Share

HTML | BBCode | Direct Link