Dear John, How Do I... Use Enums in Parameters?

You use enumerations (Enums) to restrict parameters to a predefined set of values. An Enum defines a set of symbolic values, much the same as Const, but the name of the Enum can be included in a procedure's parameter type declaration. When you use the procedure, Visual Basic's Auto List Members feature displays a list of the possible values for the argument. To see how this works, type in the following code:

Enum Number
    Zero
    One
    Two
    Three
End Enum

Sub ShowNumber(Value As Number)
    MsgBox Value
End Sub 

Sub Form_Load()
    ShowNumber One
End Sub

After you type ShowNumber in the Form_Load event procedure, Visual Basic displays the list of Enums to choose from. A similar thing happens when you use an Enum in the parameter list of a user control property. The following code shows a simple Value property in a user control:

Enum Number
    Zero
    One
    Two
End Enum

Dim mValue As Number

Property Get Value() As Number
    Value = mValue
End Property

Property Let Value(Setting As Number)
    mValue = Setting
End Property

Private Sub UserControl_ReadProperties(PropBag As PropertyBag)
    mValue = PropBag.ReadProperty("Value", One)
End Sub

Private Sub UserControl_WriteProperties(PropBag As PropertyBag)
    PropBag.WriteProperty "Value", mValue, One
End Sub

The ReadProperties and WriteProperties event procedures maintain the Value property setting in the Properties window. When you select the Value property in the Properties window, you will see a list of possible values from the Number Enum: Zero, One, and Two, as shown in Figure 4-3 following.

Another bit of helpful information is that Enums automatically coerce floating-point values to long integer values. For example, if you pass the value 0.9 to the ShowNumber procedure shown earlier, it will display 1. Also, Enums don't provide any special type checking—invalid settings are gleefully accepted. You'll have to write code to check whether a passed-in value is valid.

Figure 4-3. List of possible values for the Value property from the Number Enum in the Properties window.