Reader Level:

Use and Implemenration of the Enum Type

By Ashish Shukla on Mar 31 2013
Here we will see the use and implementation of the Enum type.
    • Like
    • Love It
    • Awesome
    • Interesting
    • It's Okay
    • Thumbs Down
  • 3.3k
  • 0

Enum is a type that is used to define a set of named constants. Each enumeration element represents a constant value. An Enum can be based on any integer type except char. By default enum is based on int. The first enumeration element has the value 0 and the next successive element has the value incremented by 1. For example the first element has the value 0, the second element has the value 1, the third element has the value 2 and so on.

In the following, we have defined an enum called Colors. By default it is based on the int type so enum elements have the values Red=0, Blue=1, Green=2, Yellow=3.

enum Colors

We can also define the enum element values explicitly as:

enum Colors

In the scenario above, Red is 2 amd Blue is 4 and since we have not defined any values for Green and Yellow it is 1 greater than the previous element's value so Green is 5 and Yellow is 6. It might be necessary to access the value of the integer element. We can access the value of the enum as:

Colors color = Colors.Green;

If we execute the code above the first statement will print the value Green and the second statement will print the value 5.

If we know the valid range of values for a variable we should declare an enum and assign to it all the possible values for the variable.

For example if we want to pass a range of values to a method, it is better to use an enumeration than to pass a wrong value accidentally. For example the following method has less of a chance of having the wrong value passed:

public void Print(Colors color)

If instead we had used the following method, the user could pass any value valid for an integer instead of the four valid values for the Colors we had defined earlier.

public void Print(int color)

All enums are derived implicitly from the System.Enum type. Since enums are derived from the System.Enum type we can use its members to get information about the enum instance.

For example to get the name of the enum having a particular value we can use the Enum.GetName() method.

If we execute the following code then we will get the value Blue since the value 4 is assigned to the enum element named Blue.

Enum.GetName(typeof(Colors), 4);

Another useful method of the Enum type is IsDefined(). It returns true if the enum contains the specified value, otherwise it returns false. For example the following code will return false since 20 is not a valid value of the Colors enumeration.

Enum.IsDefined(typeof(Colors), 20)

If instead we specify 2 then we will get the value true since 2 is a valid value for the Colors enum.