C# - Use Enum in Switch-Case statement

Using Enums in switch-case statements in C# is a great practice for several reasons. Enums (short for Enumerations) are a way to group together related constants. They make your code more readable and maintainable, especially when dealing with a set of predefined options.

Why Use Enums in Switch-Case?

  • Clarity: Enums make your code more understandable by naming each constant.
  • Reduce Errors: Using enums helps prevent mistakes such as incorrect number usage.
  • Easy to Update: Updating your options is straightforward with enums.

Let's consider an example using an enum for different types of coffee:


enum CoffeeType
{
    Espresso,
    Latte,
    Cappuccino,
    Americano
}
        
    

Here's how you might use this enum in a method with a switch-case statement:


using System;

class Program
{
    static void Main()
    {
        CoffeeType myCoffee = CoffeeType.Cappuccino;
        PrintCoffeeMessage(myCoffee);
    }

    static void PrintCoffeeMessage(CoffeeType coffee)
    {
        switch (coffee)
        {
            case CoffeeType.Espresso:
                Console.WriteLine("Strong and bold coffee!");
                break;
            case CoffeeType.Latte:
                Console.WriteLine("Coffee with lots of milk!");
                break;
            case CoffeeType.Cappuccino:
                Console.WriteLine("Coffee with frothy milk!");
                break;
            case CoffeeType.Americano:
                Console.WriteLine("Espresso with hot water!");
                break;
            default:
                Console.WriteLine("Unknown coffee type!");
                break;
        }
    }
}
	
Output

If you run this program, the output will be:


	Coffee with frothy milk!
     

This output is for the Cappuccino case in the switch statement. Using enums enhances readability and reduces errors in the code.