What is Enumeration or Enums


In this c sharp question, we will discuss about Enumerations.

Enumeration or Enums store special values. They make programs simpler by providing an efficient way to define a set of constants which they may be assigned to a variable. If you use constants directly to do this, your C# program rapidly becomes complex and hard to change. Enumeration will provide you to keep these magic constants in a distinct type. This improves code clarity and alleviates maintenance issues.

As an example if you define a variable which will represent a day of week then there are only seven meaningful values. To define those values, you can use an enumeration type, which is declared by using the enum keyword.

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

By default type of each element in the enum is int. if you need to specify another type then you need to implement it by using a colon, as shown in the bellow example

enum Days : byte { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

If you do not specify values for the each element in the list the values are automatically incremented by one. Like

Days.Sunday has a value of     0
Days.Monday has a value of    1
And so on.


class Program
    {
        enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

        static void Main(string[] args)
        {
            // These values are enum Days types.
            Days weekend_ = Days.Saturday;

            if (weekend_ == Days.Saturday)
            {
                // Will be printed.
                Console.WriteLine("Today is Weekend");
            }

            if (weekend_ == Days.Sunday)
            {
                // Will not be printed.
                Console.WriteLine("Today is Weekend");
            }
        }
    }


And also you can assign any values to the elements in the enumerator list of an enumeration type, and you can also use computed values at the program.

enum MyDayPlan
{
    Getup = 5,
    Schooling = 8,
    Swimming = 5,
    Eating = Swimming + 2
}




0 comments:

Post a Comment

Thank you very much