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
}
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.
From switch expression - pattern matching expressions using the switch keyword (Microsoft Learn)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With