enum in C#

enum

Suppose that you have to declare the week days name or month name in integer type variable, then enumeration is best option.

An enumeration is a set of named integer constants. By default the type of each element in the enum is integer. It is declared using the enum keyword. By default, the value of the first enumeration element is 0 and automatically incremented by 1 for successive element.

For creating an enumeration, the general form is

enum  name { enumeration list };
enum  Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };


Here Sunday has the value 0, Monday 1 and so on.
You can also assign any arbiter value to enum element.

enum EditMenu
    {
        Create=10,
        Delete=20,
        Add=30,
        Update=40
    };


Let us take an example on enumeration. In this example, We have created two enum Days and EditMenu.

Example

using System;
namespace ConsoleApplication1
{
    enum EditMenu
    {
        Create=10,
        Delete=20,
        Add=30,
        Update=40
    };
    
    class Program
    { enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };       
        static void Main(string[] args)
        {
            int favDay = (int)Days.Sunday;
            Console.WriteLine("My favorite day is {0}  =  {1}", Days.Sunday,favDay);
            Console.WriteLine("The value of enum ADD is = "+(int)EditMenu.Add);

            //Iterating through an enum
            Console.WriteLine("Iterating through an enum \n\n");
            foreach (Days d in Enum.GetValues(typeof(Days)))
            {
                Console.WriteLine(d.ToString());
            }        
            Console.ReadLine();
        }
    }
}


Output:
My favorite day is Sunday  =  0
The value of enum ADD is =30
Iterating through an enum

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday