Enumerators in C#


An enumeration (enum) is a special form of value type, which inherits from System.Enum and supplies alternate names for the values of an underlying primitive type. An enumeration 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 Byte, Int32, or UInt64). The fields are static literal fields, each of which represents a constant. The language you are using assigns a specific value of the underlying type to each field. The same value can be assigned to multiple fields. When this occurs, the language marks one of the values as the primary enumeration value for purposes of reflection and string conversion. The boxing rules that apply to value types also apply to enumerations. 

The general form of an enumeration declaration is as follows.

<modifier> enum <enum_name>
{
// Enumeration list
}

For example:

enum Months
{
jan, feb, mar, apr
}

By default the first enumerator has the value of zero and the value of each successive enumerator is increased by 1. For example in the above case the value jan is 0, feb is 1 and so on. Remember that the modifier can be private, public, protected or internal.

In C# enums, it is possible to override the default values. For example:

enum Months
{
jan = 10, feb = 20, mar = 30, apr=40
}

The underlying type specifies how much storage is allocated for each enumerator. However an explicit cast is needed to convert from unum type to integral types. This is why the enum types are type safe in C#.

For example: 

int x = Months.jan; is not a valid statement in C#.
int x = (int) Months.jan; is a valid statement.

The underlying type of an enumerator can be changed as follows.  

enum Months : long
{
jan,feb, mar, apr
}

Two more enum members can have the same value as follows.         

enum Months
{
jan = 1, feb = 1, mar, apr
}

All the enum members are explicitly static and so they can be accessed only with the type and not with the instances.

A complete example is shown below.         

using System;
enum Months : long
{
jan = 10,feb = 20,mar
}
class MyClient
{
public static void Main()
{
long x = (long)Months.jan;
long y = (long)Months.feb;
long z = (long)Months.mar;
Console.WriteLine("JANUARY={0},FEbriary = {1},March={2}",x,y,z);
}


The following are the restrictions apply to an enum type in C#

  1. They can't define their own methods.
  2. They can't implement interfaces.
  3. They can't define properties or indexers.

The use of enum type is superior to the use of integer constants, because the use of enum makes the code more readable and self-documenting.

Up Next
    Ebook Download
    View all

    FileInfo in C#

    Read by 9.7k people
    Download Now!
    Learn
    View all