Search code examples
c#defaultswitch-expression

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


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.


Solution

  • 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",
         _ => "???"
      });
    }