Home > DeveloperSection > Articles > Enumeration in C#

Enumeration in C#


C# C# 
Ratings:
0 Comment(s)
 985  View(s)
Rate this:

                                Enumeration in C#


Enumeration is a way to declare named constant in c#. Enumeration is declared by enum keyword in C#. Enumeration values are not using in inheritance. In enumeration each one are stands for an integer value. The value of first element symbol is represent is 0.

The syntax of Enumeration is:

 Enum<enum_name>
{  enumeration_element_list; }


For example,

enum Month{JAN,FEB,MAR,APR,MAY,JUN,JULY,AUG,SEP,OCT,NOV,DEC};


You can access the element of enumeration is using (.)Dot operator ( enum.Select_values).

In above example, using in c# program as:


namespace Enumeration1
{
    class Program
    {
        enum Month
        {
            JAN, FEB, MAR, APR,MAY, JUN, JULY, AUG, SEP, OCT, NOV, DEC
        };
        static void Main(string[] args)
        {
            //Acessing enum elements 
            Month mon = Month.DEC;   //integer vvalue =11;
            Console.WriteLine(mon);
            Month mm = Month.NOV;//integer value=10;
            if (mm == Month.NOV)
            {
                Console.WriteLine("This is Month of November");
            }
            string value = "JAN";
            //Parsing values and checking values in month
            Month mmm = (Month)Enum.Parse(typeof(Month), value);
            if (mmm == Month.JAN)
            {
                Console.WriteLine("Equals JAN.");
            }
            Console.ReadKey();
        }
    }
}

Output:


If you want to accept some input anywhere and checking to enum constant it is exists or not then we using parsing in C#.

enums enhance clarity and reduce the probability of invalid constants. We use them to represent constant values such as integers in a consistent way. enums are checked by the compiler. It is a good idea to avoid magic constants and numbers. Instead, prefer a self-documenting enum type.


Don't want to miss updates? Please click the below button!

Follow MindStick