24 September 2007

Enumerating the Enumerator

One of the joys of switching from Visual Basic to C# is the finding out about the power of the enumerator class. VB has fair enumerator support, but C# takes it to a whole new level with the enumerator class and all of it's methods.

Like VB, you can declare an enumerator and each value can have a custom numeric value. Like VB, you can declare and pass enumerator's as method arguments, which makes code very clear and easy to write.

But C# takes the enumerator many steps farther. First, the toString() method of the enumerator class prints out the actual string of the enumerator. This means that you can use it in string and numeric representations of the value.

One of the most valuable operations an enumerator class implements is the ability to inspect the class for membership. This helps make code more flexible because additions or changes to the enumerator class can flow through to other parts of the program.

For example, let's say you have a database enumerator that indicates what the database is doing at this time. This enumerator will be used for monitoring asynchronous calls to a database. The enumerator declaration would look like the following example.

Example 1: Sample Enumerator Declaration

public enum AsyncDBAction : int {
    insert,
    update,
    delete
}


Inspecting the enumerator object is very simple. In the example below, I use a foreach loop to iterate through the object and print individual member values to the console. The console will display the string representation and the numeric value for each enumerated member.

Example 2: Iterating through the Enumerator
foreach(AsyncDBAction val in Enum.GetValues(typeof(AsyncDBAction))) {
    Console.WriteLine("String value: " + val + "/numeric value " + (int)val);
}


How is this useful? If you are using the string value and the numeric value (or enumerated value), adding a new enumerated value such as 'select' or 'other' will not break your code. Simply add the new value to the enumerator and then examine it where needed to continue processing.