Switch expression precedence? #53490
-
Hello, I wrote some code today using a switch expression and got a confusing result. I expected each of these functions to return 8 when given an input of 2. But instead the GetPaddingExpr returns 2, which appears to be incorrect. After some fiddling I discovered that the switch expression was "binding" to the literal 8 instead of the entire This is somewhat unexpected to me, is this the intended behavior? using System;
Console.WriteLine($"GetPaddingExpr -> {GetPaddingExpr(2)}");
Console.WriteLine($"GetPaddingExprFixed -> {GetPaddingExprFixed(2)}");
Console.WriteLine($"GetPaddingStatement -> {GetPaddingStatement(2)}");
static int GetPaddingExpr(int value)
{
return
value % 8 switch {
0 => value,
_ => ((value / 8) + 1) * 8
};
}
static int GetPaddingExprFixed(int value)
{
return
(value % 8) switch {
0 => value,
_ => ((value / 8) + 1) * 8
};
}
static int GetPaddingStatement(int value)
{
switch(value % 8)
{
case 0: return value;
default: return((value / 8) + 1) * 8;
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Hmm, @CyrusNajmabadi, @sharwell, this might be a good candidate for us suggesting parenthesis in this case? Heuristic would be that a user probably doesn't want to do a switch expression on a numerical constant. |
Beta Was this translation helpful? Give feedback.
-
Yes. This is the intended behavior. value % (8 switch {
0 => value,
_ => ((value / 8) + 1) * 8
}); |
Beta Was this translation helpful? Give feedback.
Yes. This is the intended behavior.
switch
has higher precedence than%
, so your code is effectively parsed as if it ws: