ENUMERATED DATA TYPES

An enumerated type is a discrete list of specific values. You define the enumerated type and the values allowed. Later, if you declare a variable of that data type, it can take only those values.

For example, suppose that you are building a large application where users can have one of three access levels: clerk, supervisor, and administrator. You could define an enumerated type named AccessLevels that allows the values Clerk, Supervisor, and Administrator. Now, if you declare a variable to be of type AccessLevels, Visual Basic will only allow the variable to take those values.

The following code shows a simple example. It defines the AccessLevels type and declares the variable AccessLevel using the type. Later the MakeSupervisor subroutine sets AccessLevel to the value AccessLevels.Supervisor. Note that the value is prefixed with the enumerated type’s name.

Public Enum AccessLevels
    Clerk
    Supervisor
    Administrator
End Enum
             
Private AccessLevel As AccessLevels ' The user's access level.
             
' Set supervisor access level.
Public Sub MakeSupervisor()
    AccessLevel = AccessLevels.Supervisor
End Sub

The syntax for declaring an enumerated type is as follows:

[attribute_list] [accessibility] [Shadows] Enum name [As type]
    [attribute_list] value_name [= initialization_expression]
    [attribute_list] value_name [= initialization_expression]
   ...
End Enum

Most of these terms, including attribute_list and accessibility, are similar to those used by variable declarations. See the ...

Get Visual Basic 2012 Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.