Enum Statement

Declares an enumeration and defines its members.

Syntax

Normal form

Enum [ enumerationName ] [ As type ]
    memberName [ = value ]
    ...
End [ Enum ]

Bit flag form

Enum %FLAGS enumerationName As type
    memberName [ = value ]
    ...
End [ Enum ]

Parts

%FLAGS
Changes the Enum into a set of bit flags.
enumerationName
An identifier for the enumeration
Optional in the normal form
Required in the bit flag form
type
A primitive integer data type or a different enumerationName. It determines the range of possible values and the default starting value.
Optional in the normal form
Required in the bit flag form
memberName
Required identifier
value
Optional constant integer expression
End
Completes the Enum statement. Alternatively, you can use End Enum.

Details

An enumeration is a tightly coupled collection of numeric constants. They can make code easier to read and modify by not relying on arbitrary literals scattered throughout the code. In most cases, there is no need to explicitly set a member's value. The language can guarantee that each member is unique.

Normal enumerations

If an enumeration is not extending an existing one and the first member is not given a value explicitly, its value defaults to zero. Members of an enumeration can be positive or negative. Members can have the same value; however, the names within an enumeration must be unique.

If type is an existing enumeration, the new one is an extension of the pre-existing enumeration. As such, the default starting value is the value of the last member of the pre-existing enumeration plus one.

Bit flags

The bit flag form closely resembles the normal form, but has important differences. Whereas normal enumerations can only be assigned and compared, flags can be manipulated using the logical operators: And, Or, Xor, and Not.

Each uninitialized member is given the value that corresponds to the least significant bit not used at that point. The first member thus has a default value of one, the second is 2, the third is 4, the fourth is 8, etc.

A typeName is commonly one of the primitive integer types: Tiny, Byte, Short, UShort, Integer, UInteger, Int, UInt, Long, ULong, Huge, or UHuge.

A member can be given any value in the range of typeName. Attempting to initialize a member with a value outside of the range results in a compiler error. Members can have duplicate values; however, the names within a set of flags must be unique.

If typeName is the name of another bit field, the current statement represents an extension to the flags. The range of an extension is the same as its base.

Examples

Listing 1

Enum fruit
    apple
    banana
    cherry
End Enum

Listing 2: Extending an enumeration

Enum more_fruit As fruit
    peach
    pear
    pineapple
End Enum

Listing 3: A set of bit flags

Enum %FLAGS days As Byte
    Mon
    Tue
    Wed
    Thu
    Fri
    Sat
    Sun
End Enum

Dim weekend = days.Sat Or days.Sun

See also