Enumeration in C#

In this article we can learn about Enumeration in C#.
  • 3688

Introduction

An enumeration can be defined by enum keyword. Enumeration is a process by which we can assign multiple constant integral values to a single variable. We can define special set of values in enumeration. Enum make program simple and easier to maintain. Enumeration declaration takes the following form

[attributes] [modifiers] enum identifier [:base-type] {enumerator-list} [;]

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

enum Days {Sun, Mon, Tue, Wed, Thu, Fri };

In this enumeration, Sun is 0, Mon is 1, and so forth. Enumerators can have initializers to override the default values. For example: 

enum Days { Sun=1, Mon, Tue, Wed, Thu, Fri };

In this enumeration, the sequence of elements is forced to start from 1 instead of 0.Example

Example

using System;

using System.Collections.Generic;

using System.Text;

using System.Reflection;

namespace Enumeration

{

    public class EnumTest

    {

        enum Days

        {           

            Sun =1,

            Mon,

            Tue,

            Wed,

            Thu,

            Fri         

        }

        public static void Main()

        {

            int x;

            int y;

            x = (int)Days.Sun;

            y = (int)Days.Fri;

            Console.WriteLine("Sun = {0}", x);

            Console.WriteLine("Fri = {0}", y);

            Console.ReadLine();

        }

    }

}

In this example we can creating an application in which a variable can contain values only sunday to friday.

The output of following program

Clipboard200.jpg

© 2019 DotNetHeaven. All rights reserved.