Pre-Proposal: Switch Case Blocks #4911
Replies: 0 comments 19 replies
-
This is not true. |
Beta Was this translation helpful? Give feedback.
-
This feels extremely subtle. I think it would not at all be obvious looking at a switch statement what was going on. |
Beta Was this translation helpful? Give feedback.
-
Right. And that's very intentional. Looking at the c code, I can't tell if it intentionally falls through, or is a mistake. C# forces you to be explicit to prevent that confusion. |
Beta Was this translation helpful? Give feedback.
-
As your proposed solution demonstrates, this is resolvable in the language in the same way today. Just wrap your case sections in. |
Beta Was this translation helpful? Give feedback.
-
@CyrusNajmabadi thanks for the feedback. |
Beta Was this translation helpful? Give feedback.
-
As @CyrusNajmabadi already mentioned, this is solved with {}.
This is solvable the same way you break out of nested loops: for (int i = 0; i < 10; ++i)
{
switch (i)
{
case 4:
// Do something
break;
case 7:
goto BreakLoop;
}
}
BreakLoop:
// more code
Also already mentioned as possible today by @CyrusNajmabadi.
This is too confusing with switch expression syntax. Am I looking at a switch expression or a switch statement? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
One of my major pet peeves with C# is the
switch case
hold-over from C. Just to make my argument in full, in C cases are allowed to fall-through:This is not valid in C#: each switch block must conclude with some form of branch (
goto
,return
,break
). The entire purpose ofcase: break;
of C is not carried over, but the limitations are. For example the following needs to be used.Even worse, variable declarations are scoped according to the switch. In, what is probably, 99% of scenarios this is actually undesirable/annoying behavior (because it's only useful with
goto case
, andgoto
is generally discouraged/unused).In addition, the new
val switch {}
syntax requires a strict expression for every case (disallowingreturn
, or a block), so it does have some limitations compared toswitch (val) {}
.Proposed Changes
The following syntax is currently invalid C# in all possible contexts:
Updated missing
:
to explicit=>
This is an "escape hatch" to new syntax and behavior:
break
does not apply to the switch, instead applying to the containing loop/whatever.I'm also wondering if disallowing mixing is a good idea (i.e. you can't use
case :
andcase {}
in the same switch), but I'm not convinced either way.Any thoughts?
Beta Was this translation helpful? Give feedback.
All reactions