What is Switch Expression in C#: Simple Explanation and Example
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.
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); } }
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
breakstatements. - Useful for mapping inputs to outputs cleanly and clearly.