0

Suppose I have the following in classic C#:

public string Size(byte b)
    {
        switch (b)
        {
            case 0:
            case 1:
                return "small";
            default:
                return "big";
        }
    }

The C#8 developers correctly recognized that there is a lot of cruft in the syntax. So in C#8, I can write it more compactly like this:

    public string SizeCs8(byte b)
        => b switch
        {
            0 => "small",
            1 => "small",
            _ => "big",
        };

Definitely an improvement. But one thing bothers me. I have to repeat the value "small". Previously I didn't. I'm wondering if it is possible to do it the C#8 way without repeating the value "small"?

William Jockusch
  • 26,513
  • 49
  • 182
  • 323
  • If hte code in place of big is complex. just use a Function for it. For strings, you propably should be using constatns anyway. – Christopher Dec 13 '19 at 21:21
  • 1
    The 1st one is not valid C#. There is no fallthrough and there has to be 1 break per case, – Christopher Dec 13 '19 at 21:22
  • 1
    @Christopher It’s not a fall through, multiple values are allowed to exist for the exact same case block – Sami Kuhmonen Dec 13 '19 at 21:24
  • @SamiKuhmonen My bad, I mixed that up. However the IL that SharpLab makes for it is interesting: https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA+ABATARgLABQGAzAATakDCpA3oaQ+WRiqQLIAUAlLfY/3wYBfQaVElyOAAykAygEsAXjA7AAngBcYpYF1F0C/fgGcA7vI1gAFqVV7DRhgceOwAQ2PapIUS9LvPUhwfBz9HDAB2UgAiYwBbNwAbROiAbl8XABMYADM3AFdEjRCwl0iY4HkAczSM4VERAiEgA – Christopher Dec 13 '19 at 21:26
  • 3
    FWIW, C# 9 is likely to allow `b switch { 0 or 1 => "small", _ => "big" }` – Julien Couvreur Dec 14 '19 at 06:59
  • "Definitely an improvement" - very arguable – ASh Dec 14 '19 at 09:59

2 Answers2

2

You can try the following code for that, by adding a when clause

public string SizeCs8(byte b)
            => b switch
            {
                var x when x == 0 || x == 1 => "small",
                _ =>"big",
            };
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
1

I would consider the first (longer) version to be preferrable. Compact code is nice, but not if it compiles to more bytes.

But why not toss the switch statement? This is more compact:

public string SizeCs8(byte b) => (b <= 1) ? "small" : "big";
Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • It's a toy example. That won't be possible in general. – William Jockusch Dec 13 '19 at 21:39
  • 1
    @WilliamJockusch: It would be possible in many cases. All I can go by is what you posted. – Jonathan Wood Dec 13 '19 at 21:40
  • @WilliamJockusch Funny enough, the if syntax is what Case 1 will compile into on the IL side. However the short syntax is kept as swtich, despite the obvious overlap. | But as it turns out both the when clause and pattern matching has you covered. – Christopher Dec 13 '19 at 21:45