Open In App

C# | Enumeration (or enum)

Improve
Improve
Like Article
Like
Save
Share
Report

Enumeration (or enum) is a value data type in C#. It is mainly used to assign the names or string values to integral constants, that make a program easy to read and maintain. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. Other examples include natural enumerated types (like the planets, days of the week, colors, directions, etc.). The main objective of enum is to define our own data types(Enumerated Data Types). Enumeration is declared using enum keyword directly inside a namespace, class, or structure.

Syntax:

enum Enum_variable
{
     string_1...;
     string_2...;
     .
     .
}

In above syntax, Enum_variable is the name of the enumerator, and string_1 is attached with value 0, string_2 is attached value 1 and so on. Because by default, the first member of an enum has the value 0, and the value of each successive enum member is increased by 1. We can change this default value. 

  • Example 1: Consider the below code for the enum. Here enum with name month is created and its data members are the name of months like jan, feb, mar, apr, may. Now let’s try to print the default integer values of these enums. An explicit cast is required to convert from enum type to an integral type.

C#




// C# program to illustrate the enums
// with their default values
using System;
namespace ConsoleApplication1 {
 
// making an enumerator 'month'
enum month
{
 
    // following are the data members
    jan,
    feb,
    mar,
    apr,
    may
 
}
 
class Program {
     
    // Main Method
    static void Main(string[] args)
    {
         
        // getting the integer values of data members..
        Console.WriteLine("The value of jan in month " +
                          "enum is " + (int)month.jan);
        Console.WriteLine("The value of feb in month " +
                          "enum is " + (int)month.feb);
        Console.WriteLine("The value of mar in month " +
                          "enum is " + (int)month.mar);
        Console.WriteLine("The value of apr in month " +
                          "enum is " + (int)month.apr);
        Console.WriteLine("The value of may in month " +
                          "enum is " + (int)month.may);
    }
}
}


Output: 

The value of jan in month enum is 0
The value of feb in month enum is 1
The value of mar in month enum is 2
The value of apr in month enum is 3
The value of may in month enum is 4

 

  • Example 2: In the below code, an enumerator with name shapes is created with string data members as Circle which is by default initialized to value 0 and similarly, Square is assigned value 1 inside the class Perimeter. There is also one member function peri() which takes one parameter as a value to initializes the side/radius. Another parameter is used to judge the shape whether it is circle or square in the form of an integer value(0 or 1). Now in the main() method, an object of the Perimeter class is created. During the call of method peri(), Perimeter.shapes.circle denotes that it is a circle with value 0 and similar is the case for Perimeter.shapes.square with value 1. So inside the method, if the s1 object has value 0 then it is circle and hence its circumference is calculated and same is the case for square 
    perimeter.

C#




// C# program to illustrate the Enums
using System;
namespace ConsoleApplication2 {
     
class Perimeter {
     
    // declaring enum
    public enum shapes
    {
        circle,
        square
    }
 
    public void peri(int val, shapes s1)
    {
         
        // checking for shape to be circle
        if (s1 == 0)
        {
             
            // Output the circumference
            Console.WriteLine("Circumference of the circle is " +
                                                  2 * 3.14 * val);
        }
         
        else
        {
 
            // else output the perimeter of the square
            Console.WriteLine("Perimeter of the square is " +
                                                     4 * val);
        }
    }
}
 
class Program {
     
    // Main Method
    static void Main(string[] args)
    {
 
        Perimeter a1 = new Perimeter();
        a1.peri(3, Perimeter.shapes.circle);
        a1.peri(4, Perimeter.shapes.square);
 
    }
}
}


Output: 

Circumference of the circle is 18.84
Perimeter of the square is 16

 

Initialization of enum: As discussed above, that the default value of first enum member is set to 0 and it increases by 1 for the further data members of enum. However, the user can also change these default value.  

  • Example:
enum days {

      day1 = 1,

      day2 = day1 + 1,

      day3 = day1 + 2
      .
      .

}

In above example, day1 is assigned value ‘1’ by the user, day2 will be assigned value ‘2’ and similar is the case with day3 member. So you have to just change the value of first data member of enum, further data members of enums will increase by 1 than the previous one automatically.

Note: Now, if the data member of enum member has not been initialized, then its value is set according to rules stated below: 

  • if it is the first member, then it value is set to 0 otherwise
  • It set out the value which is obtained by adding 1 to the previous value of enum data member

Example:

enum random {

A,

B,

C = 6;

D

}

Here, A is set to 0 by default, B will be incremented to 1. However, as C is initialized with 6 so the value of D will be 7

  • Program: To demonstrate the initialization of enum data member with user define values and also some special case of initialization.

C#




// C# program to illustrate the enum
// data member Initialisation
using System;
namespace ConsoleApplication3 {
     
// enum declaration
enum days {
     
    // enum data members
    monday,
    tuesday,
    wednesday,
    thursday,
    friday,
    saturday,
    sunday
}
 
// enum declaration
enum color {
     
    // enum data members
    Red,
    Yellow,
    Blue,
     
    // assigning value yellow(1) + 5
    Green = Yellow + 5,
    Brown,
     
    // assigning value Green(6) + 3
    Black = Green + 3
 
}
 
class Program {
     
    // Main Method
    static void Main(string[] args)
    {
 
        Console.WriteLine("Demonstrating the difference "+
                      "between Special Initialisation" +
                 "cases and non-initialisation cases\n\n");
 
        // first of all non-initialized enum
        // 'days' will be displayed
        // as mentioned already, the first
        // member is initialized to 0
        // hence the output will numbers
        // from 0 1 2 3 4 5 6
 
        Console.WriteLine("Value of Monday is " +
                                    (int)days.monday);
        Console.WriteLine("Value of Tuesday is " +
                                    (int)days.tuesday);
        Console.WriteLine("Value of Wednesday is " +
                                    (int)days.wednesday);
        Console.WriteLine("Value of Thursday is " +
                                    (int)days.thursday);
        Console.WriteLine("Value of Friday is " +
                                    (int)days.friday);
        Console.WriteLine("Value of Saturday is " +
                                    (int)days.saturday);
        Console.WriteLine("Value of Sunday is " +
                                    (int)days.sunday);
 
        // Now the use of special initialisation
        // cases is demonstrated as expected Red
        // will be assigned 0 value similarly
        // yellow will be 1 and blue will be 2
        // however, green will be assigned the
        // value 1+5=6 similarly is the case
        // with brown and black
 
        Console.WriteLine("\n\nColor Enum");
 
        Console.WriteLine("Value of Red Color is " +
                                       (int)color.Red);
        Console.WriteLine("Value of Yellow Color is " +
                                     (int)color.Yellow);
        Console.WriteLine("Value of Blue Color is " +
                                      (int)color.Blue);
        Console.WriteLine("Value of Green Color is " +
                                      (int)color.Green);
        Console.WriteLine("Value of Brown Color is " +
                                      (int)color.Brown);
        Console.WriteLine("Value of Black Color is " +
                                      (int)color.Black);
    }
}
}


Output

Demonstrating the difference between Special Initialisationcases and non-initialisation cases


Value of Monday is 0
Value of Tuesday is 1
Value of Wednesday is 2
Value of Thursday is 3
Value of Friday is 4
Value of Saturday is 5
Value of Sunday is 6


Color Enum
Value of Red Color is 0
Value of Yellow Color is 1
Value of Blue Color is 2
Value of Green Color is 6
Value of Brown Color is 7
Value of Black Color is 9
  • Explanation: In above code, we have form two types of enums i.e color and days. In case of days enum, no initialization is done. So as per the rules monday will be assigned 0 and by the increment of 1, the values of tuesday, wednesday and other days will be decided. However, in case of enum color, Red will be assigned 0, Yellow will be given value 1 and so is the case of Blue. But in case of Green, its value will be decided by adding the value of Yellow with 5 which results in value 6. Again, in case of Brown, its value will be 7 and in case of Black, its value will be (7 + 3) which is 10.

Changing the type of Enum’s Data Member: By default the base data type of enumerator in C# is int. However, the user can change it as per convenience like bool, long, double, etc. 

  • Example:
// byte type
enum button : byte {

// OFF will be assigned 0
OFF,

//ON will be assigned 1
ON

// However, if we assign 100 to ON then, 
// this will give error as byte cannot hold this

}
  • Program: To demonstrate the changing of data type of members of enum

C#




// C# program to illustrate the changing
// of data type of enum members
using System;
namespace ConsoleApplication4 {
 
// changing the type to byte using :
enum Button : byte {
     
    // OFF denotes the Button is
    // switched Off... with value 0
    OFF,
 
    // ON denotes the Button is
    // switched on.. with value 1
    ON
 
}
 
class Program {
     
    // Main Method
    static void Main(string[] args)
    {
 
        Console.WriteLine("Enter 0 or 1 to know the " +
                       "state of electric switch!");
 
        byte i = Convert.ToByte(Console.ReadLine());
 
        if (i == (byte)Button.OFF)
        {
 
            Console.WriteLine("The electric switch is Off");
        }
         
        else if (i == (byte)Button.ON)
        {
            Console.WriteLine("The electric switch is ON");
        }
         
        else
        {
            Console.WriteLine("byte cannot hold such" +
                                      " large value");
        }
    }
}
}


  • Input:
1
  • Output:
Enter 0 or 1 to know the state of electric switch!
The electric switch is ON


Last Updated : 21 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads