0 day streak
csharp / intermediate
Snippet

Refined Conditional Logic with Switch Expressions

Switch expressions provide a concise way to return values based on pattern matching. Unlike traditional switch statements, they are expressions that return a result and use the lambda-like '=>' syntax, making code more readable and functional.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
public enum OrderStatus { Pending, Shipped, Delivered, Cancelled }
public string GetStatusMessage(OrderStatus status) => status switch
{
OrderStatus.Pending => "The order is waiting for processing.",
OrderStatus.Shipped => "The package is on its way.",
OrderStatus.Delivered => "Item has been received.",
_ => "Unknown or cancelled order."
};
Breakdown
1
status switch { ... }
Starts the switch expression acting on the 'status' variable.
2
OrderStatus.Pending => "..."
If status matches Pending, the expression evaluates to the string on the right.
3
_ => "..."
The discard pattern '_' acts as a default case for any unmatched values.