Why are switch expressions restricted to matching on constants? #6947
-
Just curious about the reasoning here for this. var result = operation switch
{
1 => "Case 1",
2 => "Case 2",
3 => "Case 3",
4 => "Case 4",
_ => "No case availabe"
}; is equivalent to if (operation == 1)
return "Case 1";
else if (operation == 2)
return "Case 2";
else if (operation == 3)
return "Case 3";
else if (operation == 4)
return "Case 4";
else
return "No case available"; The |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
Constants are side-effect-free. So the compiler is free to compile the switch however it wants. If there are side effects, then it's not at all clear what the semantics would be for what does or does not get executed. |
Beta Was this translation helpful? Give feedback.
-
OK thanks, much appreciated. |
Beta Was this translation helpful? Give feedback.
Constants are side-effect-free. So the compiler is free to compile the switch however it wants. If there are side effects, then it's not at all clear what the semantics would be for what does or does not get executed.