3

How to make an empty default case in switch expression in C#?

I am talking about this language feature.

Here is what I am trying:

using System;
                    
public class Program
{
    public static void Main()
    {
        int i = -2;
        var ignore = i switch {
            -1 => Console.WriteLine("foo"),
            -2 => Console.WriteLine("bar"),
            _ => ,
        };
    }
}

Also, I tried without the comma:

using System;
                    
public class Program
{
    public static void Main()
    {
        int i = -2;
        var ignore = i switch {
            -1 => Console.WriteLine("foo"),
            -2 => Console.WriteLine("bar"),
            _ =>
        };
    }
}

Still it does not want to compile. So, I tried to put an empty function:

using System;
                    
public class Program
{
    public static void Main()
    {
        int i = -2;
        var ignore = i switch {
            -1 => Console.WriteLine("foo"),
            -2 => Console.WriteLine("bar"),
            _ => {}
        };
    }
}

And it still does not work.

qqqqqqq
  • 1,831
  • 1
  • 18
  • 48
  • 1
    can you just not remove the `_` default case? if you can 100% guarantee that switch will always match one of the previous cases. – cjb110 Jun 25 '21 at 14:58
  • 1
    Which C# version have you got this to compile in? It doesn't compile [here](https://dotnetfiddle.net/EccGge). – Johnathan Barclay Jun 25 '21 at 15:00
  • @JohnathanBarclay, I updated my question. Could you try now, please? – qqqqqqq Jun 25 '21 at 15:03
  • @JohnathanBarclay, ok. It seems even the empty curly brackets do not work. I was wrong. :( – qqqqqqq Jun 25 '21 at 15:04
  • `Console.WriteLine` doesn't return anything when `switch` must return a value; it can be `var ignore = i switch { -1 => "foo", -2 => "ignore", _ => null };` – Dmitry Bychenko Jun 25 '21 at 15:08

2 Answers2

3

You are studing expressions switch expressions to be exact. All expressions must return a value; while Console.WriteLine being of type void returns nothing.

To fiddle with switch expressions you can try

public static void Main() {
  int i = -2;

  // switch expression: given i (int) it returns text (string)
  var text = i switch {
    -1 => "foo",
    -2 => "ignore",
     _ => "???" // or default, string.Empty etc.
  };

  Console.WriteLine(text);
}

Or putting expression into WriteLine:

public static void Main() {
  int i = -2;

  // switch expression returns text which is printed by WriteLine  
  Console.WriteLine(i switch {
    -1 => "foo",
    -2 => "ignore",
     _ => "???"
  });
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
2

A switch expression must be able to evaluate to a value, as with all expressions.

For your purpose, a switch statement is the correct construct:

int i = -2;
switch (i)
{
    case -1:
        Console.WriteLine("foo");
        break;
    case -2:
        Console.WriteLine("bar");
        break;
}
Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35