(Print this page)

Getting the most from Enums
Published date: Tuesday, April 13, 2010
On: Moer and Éric Moreau's web site

All projects should have some enumerations defined. Enumerations are constant values grouped under a common name. Enumerations help a lot in the readability factor. I am sure that you will agree that a value like “Red” is more meaningful then 2. And this readability does not affect the performance as the compiler can replace the word by its numerical counterpart.

You are already using enumerations everyday when calling the Framework’s methods or setting properties. For example, one of the arguments of the Show method of the MessageBox class is named buttons. Do you know the value of the MessageBoxButtons.RetryCancel enumeration value? It is 5. But who cares. The value 5 is meaningless and thanks to the Intellisense, you don’t even have to remember how the constant spells!

Downloadable code

There is no downloadable demo this month. I simply have a couple of lines in this article that you can easily copy directly to your project.

Declaring enumerations

As I have already said, enumerations are nothing more than a series of constant values grouped together using a common prefix. All these constants values are of a numeric type (integer by default).

For example, we will start with this enumeration of Pasta types:

Public Enum Pasta
    Unknown = 0
    Spaghetti = 1
    Spaghettini = 1
    Ravioli = 2
    Tortellini = 4
End Enum

The first thing you might notice in this list of values is that the value 1 is used twice with 2 different names. This is totally acceptable. But the reverse (assigning twice the same is not valid).

The second thing you might notice is that some values are missing. In my example, I don’t have the value 3 and I don’t need to provide one if I am not using one. That means that values don’t have to be contiguous.

So now, anywhere you would like to use a past value, you could declare a variable like this:

Dim myPasta As Pasta
myPasta = Pasta.Tortellini

As soon as you will type the equal sign when assigning a value to your variable, the Intellisense will popup the list of available values.

Declaring a variable as an enumeration data type doesn’t mean that you cannot assign numerical values to it. Chances are that your database will store the numeric value. So this syntax is perfectly legit and points exactly to the same value as before:

myPasta = 4

Get the name of an enumeration value

If is often useful to useful to be able to transform a numerical value into its text representation.

If you have a variable of an enumeration data type, you can simply use the ToString method like this:

MessageBox.Show(myPasta.ToString)

This will display the textual value in the enumeration (Tortellini if myPasta has the value 4).

In my Pasta enumeration, I have twice the value 1. As per my tests (but I haven’t been able to find an official reference to that), it seems that the last value is displayed. In my demo enumeration, if myPasta contains the value 1, Spaghettini would be displayed.

Get the numeric value from a name

In some other situations, you might want to get the numerical value from a name. The Parse method from the Enum class comes in handy in this scenario. Check this code:

myPasta = CType([Enum].Parse(GetType(Pasta), "Ravioli"), Pasta)

If you use this statement, be sure to encapsulate into a Try...Catch structure because if your name (and notice that it is case-sensitive) is not found, an ArgumentException will be raised.

Enumerations are not validators

You need to remember that enumerations are not directly validators. Consider this syntax:

myPasta = 5

This line is perfectly legal and won’t cause any compile problem and neither runtime problem because the myPasta variable is in fact an Integer variable and 5 is a valid value. It is not a constraint like a database constraint would prevent assigning an invalid value.

Validate a value

If you wish to validate that a value exists in an enumerations, you can simply use the IsDefined method of the Enum class like this:

If [Enum].IsDefined(GetType(Pasta), 4) Then

The first parameter of this method is the type against which you want to validate your value while the second parameter is the value to validate.

Not all enumerations are of type Integer

By default, enumerations are of type Integer. But you may want to use any other integral numerical data type that makes sense for your requirements. If you try to declare an enumeration of dates, or strings, or doubles, the compiler will prevent you from compiling.

For example, this code declares an enumeration of byte:

Public Enum Options As Byte
    Option0 = 0
    Option1 = 1
End Enum

Using reserved keyword in an enumeration

Now consider this enumeration:

Public Enum Options As Byte
    Option0 = 0
    Option1 = 1
    Option = 2
    Option 3 = 3
End Enum

There are circumstances where using a reserved keyword as the name of one of the values makes sense as in the previous example where Option (value 2) is a reserved word. But the compiler just won`t let you do as long as you surround the name with square brackets like this:

    [Option] = 2

As for the last line value containing a space (Option 3 = 3), there is nothing you can do. Even putting square brackets won’t help.

Declaring enumerations outside of classes

Very few people know that you are not limited to declare your enumerations inside a class.

I am sure that you have some global enumerations in your applications. Chances are that these global enumerations are declared inside a class and it doesn’t always make sense. Or you may have created a cGlobal class. But enumerations don’t have to be declared inside a class definition. They can just be outside any classes.

Fill a combo with the values of an enumeration

It is also easy to retrieve an array of string containing all the names of an enumeration. For example, you may want to fill a combo with these values.

A single line of code is required which this time use the GetNames method of the Enum class:

ComboBox1.DataSource = [Enum].GetNames(GetType(Pasta))

Conclusion

Enumerations help the readability of your code without sacrificing performance. After all, it is just a series of constants values! But now you are aware that even if you declared a variable of an enumeration type, assigning a value to this variable does not validate its value!


(Print this page)