articles

Enumeration in C#

Anupam Mishra3924 15-Dec-2015

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
{
    classProgram
    {
        enumMonth
        {
            JAN, FEB, MAR, APR,MAY, JUN, JULY, AUG, SEP, OCT, NOV, DEC
        };
        staticvoid 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:

Enumeration in C#


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.

You can also read these related post

https://www.mindstick.com/blog/88/enumeration-in-c-sharp


c# c# 
Updated 07-Sep-2019

Leave Comment

Comments

Liked By