C# > Core C# > Control Flow > switch Statement

Basic Switch Statement Example

This example demonstrates a basic switch statement to determine the day of the week based on an integer input.

Code Snippet

This code takes an integer input from the user, representing a day of the week. The `GetDayName` method uses a switch statement to determine the corresponding day name. Each `case` represents a different day, and the `default` case handles invalid input. The program then prints the day name or an error message to the console.

using System;

public class SwitchExample
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Enter a number representing a day of the week (1-7):");
        string input = Console.ReadLine();
        if (int.TryParse(input, out int dayOfWeek))
        {
            string dayName = GetDayName(dayOfWeek);
            Console.WriteLine(dayName);
        }
        else
        {
            Console.WriteLine("Invalid input. Please enter a number between 1 and 7.");
        }
    }

    public static string GetDayName(int day)
    {
        switch (day)
        {
            case 1:
                return "Monday";
            case 2:
                return "Tuesday";
            case 3:
                return "Wednesday";
            case 4:
                return "Thursday";
            case 5:
                return "Friday";
            case 6:
                return "Saturday";
            case 7:
                return "Sunday";
            default:
                return "Invalid Day";
        }
    }
}

Concepts Behind the Snippet

A switch statement is a control flow statement that allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is evaluated against each case. If a match is found, the code associated with that case is executed. The `break` statement is used to exit the switch statement after a match is found. The `default` case is executed if no match is found.

Real-Life Use Case

Switch statements are useful in scenarios where you have a variable that can take on a fixed number of values, and you need to perform different actions based on the value. For example, processing user commands in a text-based adventure game, handling different HTTP request types in a web server, or routing events in a GUI application.

Best Practices

  • Always include a `default` case to handle unexpected or invalid input.
  • Use `break` statements after each `case` to prevent fall-through to the next case. In modern C# (versions 7.0 and later), fall-through is not allowed by default, but it's good practice to include `break` statements for clarity.
  • Consider using enums instead of integers or strings for case values, to improve code readability and type safety.
  • For complex logic within a case, extract the code into a separate method to improve maintainability.

When to use them

Use switch statements when you have a variable that needs to be compared against several constant values. Switch statements are typically more readable and efficient than a series of `if-else if-else` statements when dealing with a fixed set of possible values.

Alternatives

The main alternative to a switch statement is a series of `if-else if-else` statements. In some cases, you could also use a dictionary to map values to actions, especially when the values are not known at compile time.

Pros

  • Improved readability compared to long chains of `if-else if-else` statements.
  • Potentially better performance, especially when the compiler can optimize the switch statement into a jump table.
  • Clearer structure for handling multiple possible values of a variable.

Cons

  • Can only compare against constant values.
  • Can become less readable when dealing with complex logic within each case.
  • Requires a `break` statement after each case to prevent fall-through (though this is enforced in newer C# versions).

FAQ

  • What happens if I don't include a `break` statement in a case?

    In older versions of C#, if you don't include a `break` statement, execution will 'fall through' to the next case, which is often undesirable. However, in modern C# (versions 7.0 and later), fall-through is not allowed by default and will result in a compile-time error unless you explicitly use the `goto case` statement to indicate intentional fall-through.
  • Can I use strings in a switch statement?

    Yes, you can use strings in a switch statement in C#.
  • Can I use enums in a switch statement?

    Yes, using enums in a switch statement is a good practice for readability and type safety.