0
0
C Sharp (C#)programming~5 mins

Enum with switch pattern in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Enums help us name a set of related values. Using a switch pattern with enums lets us choose actions based on these named values clearly and simply.

When you have a fixed set of options like days of the week or colors.
When you want to run different code depending on a specific named value.
When you want your code to be easy to read and understand choices.
When you want to avoid many if-else statements for clear decision making.
Syntax
C Sharp (C#)
enum EnumName
{
    Value1,
    Value2,
    Value3
}

switch (enumVariable)
{
    case EnumName.Value1:
        // action for Value1
        break;
    case EnumName.Value2:
        // action for Value2
        break;
    default:
        // action for other values
        break;
}

Use enum to define named constants.

The switch statement checks the enum value and runs matching code.

Examples
This example prints a message based on the day.
C Sharp (C#)
enum Day
{
    Monday,
    Tuesday,
    Wednesday
}

Day today = Day.Monday;
switch (today)
{
    case Day.Monday:
        Console.WriteLine("Start of the week");
        break;
    case Day.Tuesday:
        Console.WriteLine("Second day");
        break;
    default:
        Console.WriteLine("Another day");
        break;
}
This example shows how to handle all enum values without a default case.
C Sharp (C#)
enum Color { Red, Green, Blue }
Color favorite = Color.Green;
switch (favorite)
{
    case Color.Red:
        Console.WriteLine("You like red.");
        break;
    case Color.Green:
        Console.WriteLine("You like green.");
        break;
    case Color.Blue:
        Console.WriteLine("You like blue.");
        break;
}
Sample Program

This program uses an enum for traffic lights and prints what to do for each color using a switch statement.

C Sharp (C#)
using System;

enum TrafficLight
{
    Red,
    Yellow,
    Green
}

class Program
{
    static void Main()
    {
        TrafficLight light = TrafficLight.Yellow;

        switch (light)
        {
            case TrafficLight.Red:
                Console.WriteLine("Stop");
                break;
            case TrafficLight.Yellow:
                Console.WriteLine("Get ready");
                break;
            case TrafficLight.Green:
                Console.WriteLine("Go");
                break;
            default:
                Console.WriteLine("Unknown signal");
                break;
        }
    }
}
OutputSuccess
Important Notes

Always include a default case to handle unexpected values.

Enums make your code easier to read than using numbers or strings.

Switch statements with enums are faster and clearer than many if-else checks.

Summary

Enums give names to fixed sets of values.

Switch statements let you run code based on enum values clearly.

This combination makes your code easier to read and maintain.