Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSharp switch expression with or and default guard with condition

What is the behavior to be expected when using switch expressions with or and a default guard with a condition? I'd expect that anything that qualifies for one of the or statements or for the default guard would enter that case, but apparently this is not how this works.

Consider the following example

var types = new HashSet<string>();
types.Add("a");
types.Add("b");
types.Add("c");

var input = "d";
var result = input switch {
   "d" or _ when types.Contains(input) => "1",
   _ => "2",
};

        
Console.WriteLine(result); //I'd expect "1" but I get "2"
like image 985
baywet Avatar asked Oct 20 '25 11:10

baywet


1 Answers

Documentation states:

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

First arm of your expression violates this, because guard is present, and guard evaluates to false. So the result is that of a second arm ("2").

like image 138
Evk Avatar answered Oct 23 '25 00:10

Evk



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!