C# Interview Question #83

What is a switch expression in C#?

Advanced C# Language Features Mid-Level Intermediate

Quick Interview Answer

A switch expression is a concise expression-based form of switch that returns a value based on pattern matching.

Detailed Explanation

A switch expression is a concise expression-based form of switch that returns a value based on pattern matching.

Unlike the traditional switch statement, a switch expression is especially useful when the purpose of the branching logic is to calculate or select a value.

The discard pattern _ is commonly used as the final fallback case. Switch expressions work well with enums, records, property patterns, and other modern pattern-matching features.

Code Example

string GetStatusText(int status) => status switch
{
    1 => "Pending",
    2 => "Approved",
    3 => "Rejected",
    _ => "Unknown"
};