Enumeration ( Enum)

It is a value type used to assign a set of constant names to a group of integer values
making the constants more readable.
This Enumeration is declared inside a namespace or class or structure using the enum keyword.

Syntax:

enum Enum_Name
{
X1;
X2;
X3;
..so on
}

 

By default, the first constant value is 0 and the next values are increased by 1.

Example 1:

 

using System;
namespace SampleProgram {
  enum Rating {
    VeryPoor;
    Poor;
    Average;
    Good;
    Excellent;
  }
  class MySample {
    public static void Main(string[] args) {
      Console.WriteLine(“VeryPoor Rating: ” + (int) Rating.VeryPoor);
      Console.WriteLine(“Poor Rating: ” + (int) Rating.Poor);
      Console.WriteLine(“Average Rating: ” + (int) Rating.Average);
      Console.WriteLine(“Good Rating: ” + (int) Rating.Good);
      Console.WriteLine(“Excellent Rating: ” + (int) Rating.Excellent);
    }
  }
}

 

The output will be:

very poor Rating :0
Poor Rating:1
Average Rating:2
Good Rating :3
Excellent Rating:4

 

Example 2:

 

enum MyCustomEnum
{
Y1,
Y2,
Y3,
Y4=8,
Y5,
Y6
}

 

Here the integer values will assign from 0 as default. As the Y4 is assigned to value 8,
the next Y5 is incremented by 1 with the precedence value 8 then the value of Y5 is 9 (8+1)
as below.

0,1,2,8,9,10

 

Related Tutorials