0
0
CsharpConceptBeginner · 4 min read

What is Switch Expression in C#: Simple Explanation and Example

A switch expression in C# is a concise way to select a value based on matching patterns or cases. It returns a result directly and is more readable than the traditional switch statement. Introduced in C# 8.0, it simplifies conditional logic by using expressions instead of statements.
⚙️

How It Works

Think of a switch expression like a vending machine that gives you a snack based on the button you press. Instead of writing many lines to check each button, the switch expression lets you quickly say: "If button A, then snack X; if button B, then snack Y." It evaluates the input and immediately returns the matching result.

Unlike the older switch statement that uses multiple lines and requires break commands, the switch expression is a single expression that produces a value. It uses patterns to match the input and arrows (=>) to specify the result for each case. This makes your code shorter, clearer, and less error-prone.

💻

Example

This example shows how to use a switch expression to get the name of a day based on its number.

csharp
using System;

class Program
{
    static void Main()
    {
        int dayNumber = 3;
        string dayName = dayNumber switch
        {
            1 => "Monday",
            2 => "Tuesday",
            3 => "Wednesday",
            4 => "Thursday",
            5 => "Friday",
            6 => "Saturday",
            7 => "Sunday",
            _ => "Invalid day"
        };

        Console.WriteLine(dayName);
    }
}
Output
Wednesday
🎯

When to Use

Use switch expressions when you want to select a value based on different conditions in a clean and readable way. They are great for replacing long if-else chains or traditional switch statements that return values.

For example, you can use switch expressions to map codes to descriptions, convert enums to strings, or handle different input types with pattern matching. They help keep your code simple and easy to maintain.

Key Points

  • Switch expressions return a value directly, unlike switch statements.
  • They use pattern matching and arrows (=>) for concise syntax.
  • Introduced in C# 8.0 to simplify conditional logic.
  • They reduce errors by eliminating the need for break statements.
  • Useful for mapping inputs to outputs cleanly and clearly.

Key Takeaways

Switch expressions provide a concise way to return values based on matching cases.
They improve code readability by replacing long if-else or switch statements.
Switch expressions use pattern matching and arrows for clear syntax.
Introduced in C# 8.0, they help avoid common switch statement errors.
Ideal for mapping inputs to outputs in a clean, maintainable way.