Home > Net >  CSharp switch expression with or and default guard with condition
CSharp switch expression with or and default guard with condition

Time:09-22

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"

CodePudding user response:

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").

  • Related