Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a pattern matching switch statement guaranteed to happen in order?

In the following code, is result guaranteed to be 1, or are there no ordering guarantees and could it also return 2?

record Foo
{
    bool X { get; init; }
    bool Y { get; init; }
    bool Z { get; init; }
}

var foo = new Foo { X = true, Y = true };
var result = foo switch
{
    { X: true } => 1,
    { Y: true } => 2,
    { Z: true } => 3,
    _ => 0
}
like image 711
Rick de Water Avatar asked Oct 22 '25 06:10

Rick de Water


1 Answers

This is a switch expression, not a switch statement.

Yes.

The result of a switch expression is the value of the expression of the first switch expression arm whose pattern matches the input expression and whose case guard, if present, evaluates to true. The switch expression arms are evaluated in text order.

From switch expression - pattern matching expressions using the switch keyword (Microsoft Learn)

like image 165
Orion Avatar answered Oct 23 '25 20:10

Orion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!