C#: Enumeration

This entry is part 69 of 71 in the series C#

The enum keyword is used to declare an enumeration, a distinct type that consists of a set of constants called the enumerator list.

By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.

Enumerators can use initializers to override the default values, as shown in the following example.

enum Months {Jan=1, Feb, Mar, Apr, May, Jun, July };

using System;

namespace Enumeration
{
    public class EnumTest
    {
        enum Months {Jan, Feb, Mar, Apr, May, Jun, July };

        static void Main()
        {
            int x = (int)Months.Mar;
            int y = (int)Months.Jun;
            Console.WriteLine("Mar = {0}", x);
            Console.WriteLine("Months.Mar = {0}", Months.Mar);
            Console.WriteLine("Jun = {0}", y);
            Console.WriteLine("Months.Jun = {0}", Months.Jun);

            Console.ReadKey();
        }
    }
}

enum1

If we change the default value of the first enumerator.
using System;

namespace Enumeration
{
    public class EnumTest
    {
        enum Months {Jan = 1, Feb, Mar, Apr, May, Jun, July };

        static void Main()
        {
            int x = (int)Months.Mar;
            int y = (int)Months.Jun;
            Console.WriteLine("Mar = {0}", x);
            Console.WriteLine("Months.Mar = {0}", Months.Mar);
            Console.WriteLine("Jun = {0}", y);
            Console.WriteLine("Months.Jun = {0}", Months.Jun);

            Console.ReadKey();
        }
    }
}

The output will be:

enum2

Series Navigation<< C#: Try catch block
C#: Generic swap functions >>
Posted in