C# program to demonstrate the Enum

Here, we are going to demonstrate the Enum in C#?
Submitted by Nidhi, on November 08, 2020

Here, we will create an enumeration and then access those elements and print their values.

Program:

The source code to demonstrate the enumeration is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to demonstrate the Enum

using System;

enum COLOR
{
    RED,GREEN,YELLOW,BLACK,WHITE, BLUE
}

class EnumDemo
{
    static void PrintColor(COLOR color)
    {
        switch (color)
        { 
            case COLOR.RED:
                Console.WriteLine("Color is Red,    value: "+COLOR.RED);
                break;
            case COLOR.GREEN:
                Console.WriteLine("Color is Green,  value: " + COLOR.GREEN);
                break;
            case COLOR.YELLOW:
                Console.WriteLine("Color is Yellow, value: " + COLOR.YELLOW);
                break;
            case COLOR.BLACK:
                Console.WriteLine("Color is Black,  value: " + COLOR.BLACK);
                break;
            case COLOR.WHITE:
                Console.WriteLine("Color is White,  value: " + COLOR.WHITE);
                break;
            case COLOR.BLUE:
                Console.WriteLine("Color is Blue,   value: " + COLOR.BLUE);
                break;
        }
    }
    static void Main(string[] args)
    {
        PrintColor(COLOR.RED    );
        PrintColor(COLOR.GREEN  );
        PrintColor(COLOR.BLUE   );
    }
}

Output:

Color is Red,      value: RED
Color is Green,  value: GREEN
Color is Blue,     value: BLUE
Press any key to continue . . .

Explanation:

In the above program, we created an enum COLOR that contain constants with color names. Here, we also created a class EnumDemo that contains two static methods PrintColor() and Main().

In the PrintColor() method, we created a switch block, here, we printed the color value based on enum constant passed into the method.

In the Main() method, we called the PrintColor() method with different values of a COLOR enum.





Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.