Working With Enumerations in C#


.Net Enumeration Basics

Enumerations or simply Enums in short provide convenient ways to create and access named numeric constants. These constants can have custom Indexable values that represent each individual element. Unlike arrays, they can have values which are not incremental in steps of ‘1’. Also, these values can be of types other than integers (which is the default) such as bytes, Boolean etc.

A single Enumeration itself has a group of values associated with it. We create an Enum Object before attempting to use the functions that are offered. This value when used with a dot operator on an Enumeration gives the state of the Enumeration Object. When we initialize new Enums of a previously defined Enum, we don’t use the new operator. The new Enums are almost immediately created and initialized to an initial value within the Enum.

Create an Enum



Lets take an example to illustrate this. The traffic lights should provide a simple but complete example on how to create and use an Enumeration. Start off by creating the Enumeration itself:


enum TrafficLights
        
 {
       Red,
       Yellow,
       Green
 };

Note how commas are used instead of semicolons used otherwise. Next, create a traffic lights object to make use of the Enum. The Enum is initialized to the value Red:



TrafficLights Light1 = TrafficLights.Red;


To change the value of this Enum from Red to say, Green:



Light1 = TrafficLights.Green;


Converting Enums between their Name and Value


Now we shall see what value is possessed by an Enum. This value is actually the integer value of the present selected string value. Casting explicitly can bring out the value of the selection. To perform a conversion, we must know the corresponding values of our traffic lights first. Since we have not explicitly defined values, the implicit values are 0 for Red, 1 for Yellow and 2 for Green. Lets suppose we have an Integer that takes in the present underlying Integer value of the Traffic Signal:


int I;

I = (int)Light1;

The method used above is called Explicit Casting. Simply put the variable type in brackets before the Enum to convert it to its integral value.

We can also do the reverse i.e. we can get the Enum members from their Integer values. Just use the Explicit Cast again. See below how to create a Red traffic signal from its Integer value 0:



TrafficLights LightR = (TrafficLights)0;


Now that we know Enums have Integer values associated with them, then it is only logical to think that they can be used to perform logical operations as well. Suppose we have a traffic light and want to check if its not Red i.e. Green or Yellow. Then we can use the following code to apply the check through an if statement:


if (LightR > 0)

{

                //Do This

}

Custom Search