This project is read-only.

Modern syntax for switch

Topics: C# Language Design
Sep 5, 2014 at 11:40 AM
New features of C#6 such as expression bodies and primary constructors do a good job at making code cleaner and less verbose.

However, it would be nice to reduce verbosity inside method bodies as well. In my opinion, one of the worst offenders right now is switch with its ancient syntax that requires break in each case.

For a better example, here is PowerShell syntax:
switch($x) {
    'a' { write 'a' }
    'b' { write 'b' }
I think it would be really useful if switch syntax was simplified to something like this:
switch (x) {
      5: Write("5!");
    "a": Write("a!");
     x < 3 && x > 2:
         Write("Between 2 and 3!");
Making case optional allows clear disambiguation between "legacy case" (fall-through, requires break) and "modern case" (no fall-through, no break). I am not sure this syntax would work as proposed (ControlFlow points at potential ambiguities with labels), but I think it shows the idea.

In the third example here, I use switch variable itself in a condition — again, this is not necessarily the best design, and just demonstrates an idea. For example, VB uses a special keyword (Is < 3). However I don't immediately see why variable name wouldn't work, and for longer switch conditions we could allow switch (var y = ...) and use that variable within switch scope.

Another nice thing would be switch-expressions, e.g. var r = switch(x) { "a": 1, "b": 2 };, though those are less essential.