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

Time:11-17

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
}

CodePudding user response:

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.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression

  • Related