简体   繁体   中英

What is the operator precedence for the new C# 8.0 switch expressions?

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?

The Roslyn source suggests that indeed switch expressions have fairly high precedence, but there are some things with higher precedence such as ranges, unary operators, and casts. See here and here in the Roslyn source.

Example code that demonstrates higher precedence of SyntaxKind.LogicalNotExpression ( Precende.Unary ):

var foo = false;
var bar = !foo switch {
    true => "true",
    false => "false"
};
Console.WriteLine(bar); // writes "true"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM