Enumerations

An enumeration is a type whose values are explicitly named by the creator of the type. The .NET Framework and Visual Basic .NET define many enumerations for their and your use. In addition, Visual Basic .NET provides syntax for defining new enumerations. Here is an example:

Public Enum Rainbow
   Red
   Orange
   Yellow
   Green
   Blue
   Indigo
   Violet
End Enum

This declaration establishes a new type, called Rainbow. The identifiers listed within the body of the declaration become constant values that may be assigned to variables of the Rainbow type. Here is a declaration of a variable of type Rainbow and an initial assignment to it:

Dim myRainbow As Rainbow = Rainbow.Blue

Note that the value name is qualified by the type name.

Enumerations are value types that implicitly inherit from the .NET Framework’s System.Enum type (which in turn inherits from System.ValueType). That means that every enumeration has access to the members defined by System.Enum. One such member is the ToString method, which returns a string containing the name of the value. This is handy for printing:

Dim myRainbow As Rainbow = Rainbow.Blue
Console.WriteLine("The value of myRainbow is: " & myRainbow.ToString(  ))

This code results in the following output:

The value of myRainbow is: Blue

The values of an enumeration are considered as ordered. Thus, comparisons are permitted between variables of the enumeration type:

Dim myRainbow As Rainbow Dim yourRainbow As Rainbow ' ... If myRainbow < yourRainbow Then ' ... End If ...

Get Programming Visual Basic .NET 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.