capypad
0 day streak
csharp / intermediate
Snippet

Pattern Matching Switch Expressions

Switch expressions provide a more concise syntax for pattern matching. They allow testing object properties directly and returning a value based on the first match.

snippet.csharp
csharp
1
2
3
4
5
6
7
string priority = task switch
{
{ IsCompleted: true } => "None",
{ IsUrgent: true, DaysLeft: < 2 } => "Critical",
{ IsUrgent: true } => "High",
_ => "Standard"
};
Breakdown
1
{ IsUrgent: true, DaysLeft: < 2 }
Property pattern matching combined with a relational pattern (< 2).
2
_ => "Standard"
The discard pattern acting as the default case if no other patterns match.