A switch expression returns a value from matching cases.

switch expression A switch expression selects one result based on a matched pattern.

Switch Expression

command
SwitchExpression.cs
Replay: real traced execution (multi-file project)
using System;

class Program
{
    static void Main()
    {
        string command = "start";
        string action = command switch
        {
            "start" => "run",
            "stop" => "halt",
            _ => "wait"
        };

        Console.WriteLine($"command={command}");
        Console.WriteLine($"action={action}");
    }
}
using System;

class Program
{
    static void Main()
    {
        string command = "stop";
        string action = command switch
        {
            "start" => "run",
            "stop" => "halt",
            _ => "wait"
        };

        Console.WriteLine($"command={command}");
        Console.WriteLine($"action={action}");
    }
}
using System;

class Program
{
    static void Main()
    {
        string command = "pause";
        string action = command switch
        {
            "start" => "run",
            "stop" => "halt",
            _ => "wait"
        };

        Console.WriteLine($"command={command}");
        Console.WriteLine($"action={action}");
    }
}
  1. command ← start, action ← run

    4{5    static void Main()6    {7        string command→ start = "start"; //@command="stop", "pause"8        string action→ run = commandstart switch9        {10            "start" => "run",11            "stop" => "halt",12            _ => "wait"13        };1415        Console.WriteLine($"command={commandstart}");16        Console.WriteLine($"action={actionrun}");17    }
    outputcommand=start
    action=run
  1. command ← stop, action ← halt

    4{5    static void Main()6    {7        string command→ stop = "stop";8        string action→ halt = commandstop switch9        {10            "start" => "run",11            "stop" => "halt",12            _ => "wait"13        };1415        Console.WriteLine($"command={commandstop}");16        Console.WriteLine($"action={actionhalt}");17    }
    outputcommand=stop
    action=halt
  1. command ← pause, action ← wait

    4{5    static void Main()6    {7        string command→ pause = "pause";8        string action→ wait = commandpause switch9        {10            "start" => "run",11            "stop" => "halt",12            _ => "wait"13        };1415        Console.WriteLine($"command={commandpause}");16        Console.WriteLine($"action={actionwait}");17    }
    outputcommand=pause
    action=wait