Software Development

Simplify programming with enumerations in VB6

VB6 lets you create enumerations, which are programmer-defined data types that can take on a set of constant values. Peter Aitken shows you how to create and use enumerations.

VB6 lets you create enumerations, which are programmer-defined data types that can take on a set of constant values. The use of enumerations can simplify certain programming tasks and make your program code easier to read. In this article, I'll show you how to create and use enumerations.

You create an enumeration with the Enum...End Enum statement:

Public Enum EnumName
    ConstantName1
    ConstantName2
    ...
    ContantNameN

End Enum

EnumName is the name of the enumeration following VB's usual variable naming rules. Each constant name (you can have as many as you like) becomes a member of the enumeration. By default, the constants are automatically assigned numerical values in order, starting with 0. Here's an example:

Public Enum Flavor
    flVanilla
    flChocolate
    flCoffee
    flStrawberry
End Enum

This results in the constant flVanilla being equal to 0, flClocolate being equal to 1, and so on. Usually, the actual numerical values of the constants in an enumeration do not matter, but if you want to assign specific values you can:

Public Enum Flavor
    flVanilla = 2
    flChocolate = 4
    flCoffee = 8
    flStrawberry = 16
End Enum

Note the use of a prefix, in this example "fl," as part of each constant name. This helps to identify the constant, when used in code, as a member of an enumeration. It's not required, but it can make code easier to read.

Once you define an enumeration, it becomes available in your program as a data type along with VB's built-in data types. You can declare variables of this type as shown here:

Dim MyFavoriteFlavor As Flavor

You can use the type for procedure arguments:

Public Sub MakeCone(f As Flavor)
...
End Sub

Finally, you can use the type as a return value of a function:

Public Function Taste() As Flavor
...
End Function

When you are typing code, the VB editor will display a drop-down list of enumeration members for you to choose from, which is a real convenience. If you try to use an incorrect value (i.e., one that's not in the enumeration), you'll receive an error message.

In terms of saving coding time and preventing errors, enumerations have a place in every VB programmer's toolkit.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

0 comments