How to: Declare Enumerations
You create an enumeration with the Enum statement in the declarations section of a class or module. You cannot declare an enumeration within a method. To specify the appropriate level of access, use Private, Protected, Friend, or Public.
An Enum type has a name, an underlying type, and a set of fields, each representing a constant. The name must be a valid Visual Basic 2005 qualifier. The underlying type must be one of the integer types—Byte, Short, Long or Integer. Integer is the default. Enumerations are always strongly typed and are not interchangeable with integer number types.
Enumerations cannot have floating-point values. If an enumeration is assigned a floating-point value with Option Strict On, a compiler error results. If Option Strict is Off, the value is automatically converted to the Enum type.
For information on names, and how to use the Imports statement to make name qualification unnecessary, see Enumerations and Name Qualification.
To declare an enumeration
Write a declaration that includes a code access level, the Enum keyword, and a valid name, as in the following examples, each of which declares a different Enum.
Private Enum SampleEnum SampleMember End Enum Public Enum SampleEnum2 SampleMember End Enum Protected Enum SampleEnum3 SampleMember End Enum Friend Enum SampleEnum4 SampleMember End Enum Protected Friend Enum SampleEnum5 SampleMember End Enum
Define the constants in the enumeration. By default, the first constant in an enumeration is initialized to 0, and subsequent constants are initialized to a value of one more than the previous constant. For example, the following enumeration, Days, contains a constant named Sunday with the value 0, a constant named Monday with the value 1, a constant named Tuesday with the value of 2, and so on.
Public Enum Days Sunday Monday Tuesday Wednesday Thursday Friday Saturday End Enum
You can explicitly assign values to constants in an enumeration by using an assignment statement. You can assign any integer value, including negative numbers. For example, you may want constants with values less than zero to represent error conditions. In the following enumeration, the constant Invalid is explicitly assigned the value –1, and the constant Sunday is assigned the value 0. Because it is the first constant in the enumeration, Saturday is also initialized to the value 0. The value of Monday is 1 (one more than the value of Sunday); the value of Tuesday is 2, and so on.
Public Enum WorkDays Saturday Sunday = 0 Monday Tuesday Wednesday Thursday Friday Invalid = -1 End Enum
This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Visual Basic Language. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).
To declare an enumeration explicitly
Write a declaration using the following syntax.
Public Enum MyEnum As Byte Zero One Two End Enum