Enumerators in C# 



An enumeration (enum) is a special form of value type, which inherits from System.Enum and supplies an alternate name for an underlying primitive type. An enum type has a name, an underlying type, and a set of fields. The underlying type must be one of the built-in signed or unsigned integer types (such as Int16, Int32, or Int64). The fields are static literal fields, each of which represents a constant. Each field is assigned a specific value of the underlying type by the language compiler

Following is an example illustrating an enum:

class Class1
{

static void Main ( string [ ] args )
{

Console.WriteLine ( color.red ) ;

}

}

enum color
{

red, blue, green

}

Output: red

We can also change the underlying data type (which is int by default) as in the following snippet:

public class Class1
{

static void Main ( string [ ] args )
{

Console.WriteLine ( color.red ) ;

}

}

enum color:byte
{

red = 8, blue, green

}

Output :- red

But here we have to be careful that we should not use a value, which is out of range, for example assigning a value like 500 to red in this program will result in error.

To check the value of blue we write 

Console.WriteLine ( (int) color.blue ) ; 

And we get 9.

This is because every next member value increments by one.

Internally enum is a sealed class, and it cannot even inherit from a sealed class.

An enum cannot have two members with the same name and the following code

class Class1
{

static void Main ( string [ ] args )
{

Console.WriteLine ( (int) color.blue ) ; 

}

}

enum color
{

red, blue, green, red

}

flashes an error: class enum1.color already consists a definition for ‘red’.


Printing all members

Here’s a program illustrating how to print out values of an enum.

class Class1

{

static void Main ( string [ ] args )
{

string [ ] names ;
names = color.GetNames ( typeof ( color ) ) ;
foreach ( string i in names )
{

Console.WriteLine ( i ) ;

}

}

}

enum color
{

red, blue, green, yellow, brown

}

And the output is:
red
blue
green
yellow
brown.

We created an array of strings called names. The GetNames( ) function returns all the names of the specified enum. We pass the typeof the enum to this function. Then using the foreach statement we print these names out.

 

Comparing Value

Here’s a program illustrating how to compare two values of an enum.

 

class Class1
{

static void Main ( string [ ] args )
{

Console.WriteLine ( color.green.CompareTo ( color.red ) ) ;
Console.WriteLine ( color.red.CompareTo ( color.yellow ) ) ;

}

}

enum color
{

red, blue, green, yellow, brown

}

Here the value of green is greater than red so the output is 1 and value of red is less than yellow which results in a –1.