Enumeration in C#

Updated on     Kisan Patel

Enumeration is a user defined value type. Enumerations contain a list of named constants that allows you to assign symbolic names to integral values. The list is called an enumerator list here while its contents are called enumerator identifiers.

Enumerations are defined in C# using the enum keyword. The enumerator identifiers (named constants) are separated using a comma ‘,’.

enum Color
{
  Red = 1,
  Green,
  Yellow
}

Now, lets take example to understand concept of enumeration in C#.

namespace EnumeraionsExa
{
    enum Color
    {
        Red = 1,
        Green,
        Yellow
    }
    class Program
    {
        public static void printColor(int i)
        {
            Color col = (Color)i;
            switch (col)
            {
                case Color.Red:
                    Console.WriteLine("The selected color is Red");
                    break;
                case Color.Green:
                    Console.WriteLine("The selected color is Green");
                    break;
                case Color.Yellow:
                    Console.WriteLine("The selected color is Yellow");
                    break;
                default:
                    Console.WriteLine("The number is not assigned to any color");
                    break;
            }
        }

        public static void Main(string[] args)
        {
            Console.WriteLine("Please select 1 for Red, 2 for Green, and 3 for Yellow");
            string str = Console.ReadLine();
            int colInt = Int32.Parse(str);
            printColor(colInt);
            Console.ReadLine();
        }   
    }
}

Here we have defined an enumeration, Color, and defined three values Red, Green and Yellow to it. The Red member is initialized with 1; therefore, the value of Green and Yellow will be authomatically 2 and 3, respectively.

The code line Color col = (Color)i creates an object of Color that is used to access the member of enumeration.

the output of the above program…

enum-example

Enumerations internally use integral values to represent the different named constants. The underlying type of an enumeration can be any integral type (e.g. int, byte, etc). The default type is int. In fact, when we declare an enumeration, its items are assigned successive integer values starting from zero.

We can also define the values for the Enumerator identifier explicitly while defining new enumerations, like:

enum Temperature
{
   BoilingPoint = 100,
   FreezingPoint = 0
}

Now, when we try to print the value of either Temperature.BolilingPoint or Temperature.FreezingPoint, it will display the assigned values and not the default values.

For Example,

int i = (int) Temperature.BoilingPoint;
Console.WriteLine("the integral value of BoilingPoint is " + Temperature.BoilingPoint);
// print the "the integral value of BoilingPoint is 100"

C#

Leave a Reply