Introduction of Enum in C#

Enumerations are special sets of named values which all maps to a set of numbers, usually integers.
  • 2763

Introduction

Enumerations are special sets of named values which all maps to a set of numbers, usually integers. They come in handy when you wish to be able to choose between a set of constant values and with each possible value relating to a number they can be used in a wide range of situations. An enum in C# is a value type that is used to represent a set of fixed distinct values so that it can be used later in program logic. An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable. For example, assume that you have to define a variable whose value will represent a day of the week. There are only seven meaningful values which that variable will ever store. To define those values, you can use an enumeration type, which is declared by using the enum keyword. As you will see in our example, enumerations are defined above classes inside our namespace. This means we can use enumerations from all classes within the same namespace.

Example : This is a simple example of a Enumerations in C#.

Code

using System;

namespace ConsoleApplication1

{

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

  class Program

  {

    static void Main(string[] args)

    {

     Days day = Days.Monday;

     Console.WriteLine((int)day);

     Console.ReadLine();

      }

    }

}

 

© 2020 DotNetHeaven. All rights reserved.