|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
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.
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.
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.
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.
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.
To declare an enumeration explicitly
Write a declaration using the following syntax.