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
switchexpression is the value of the expression of the firstswitchexpression arm whose pattern matches the input expression and whose case guard, if present, evaluates totrue. Theswitchexpression arms are evaluated in text order.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression
