Nullable and Pattern Matching
Switch Expression
A switch expression returns a value from matching cases.
switch expression
A switch expression selects one result based on a matched pattern.
Switch Expression
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}");
}
}
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
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
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