I just upgraded my current project to the newly released .NET Standard 2.1 and C# 8.0, and decided to convert some large switch
statements into the new, much more compact expression syntax.
Since the returned values are further used in some computations, I was wondering how the new switch
expressions behave when the input variable is next to an operator.
Take the following example for string concatenation:
string input = Console.ReadLine();
string output = "Letter: " + input switch
{
"1" => "a",
"2" => "b",
_ => "else"
};
Console.WriteLine(output);
I guess that the switch
binds very strongly to the input
variable, and thus is evaluated first. And indeed, this prints Letter: a
, when I type 1
.
But my question now is: Does this behavior apply to any operator?
From my experiments, I was not able to identify a condition where the above hypothesis does not hold, but that obviously does not mean that there isn't a case that I have missed. The docs also don't seem to mention operator precedence in context of switch
expressions. Or do I have some deeper misunderstanding here?