Control Flow
Switch Statements
A switch statement chooses a case based on a value.
switch case
A switch case handles one matching value inside a switch statement.
Switch Statements
SwitchStatement.cs
Replay: real traced execution (multi-file project)
using System;
class Program
{
static void Main()
{
int day = 2;
string label;
switch (day)
{
case 1:
case 2:
case 3:
case 4:
case 5:
label = "weekday";
break;
case 6:
case 7:
label = "weekend";
break;
default:
label = "invalid";
break;
}
Console.WriteLine($"day={day}");
Console.WriteLine($"label={label}");
}
}
using System;
class Program
{
static void Main()
{
int day = 6;
string label;
switch (day)
{
case 1:
case 2:
case 3:
case 4:
case 5:
label = "weekday";
break;
case 6:
case 7:
label = "weekend";
break;
default:
label = "invalid";
break;
}
Console.WriteLine($"day={day}");
Console.WriteLine($"label={label}");
}
}
using System;
class Program
{
static void Main()
{
int day = 9;
string label;
switch (day)
{
case 1:
case 2:
case 3:
case 4:
case 5:
label = "weekday";
break;
case 6:
case 7:
label = "weekend";
break;
default:
label = "invalid";
break;
}
Console.WriteLine($"day={day}");
Console.WriteLine($"label={label}");
}
}
day ← 2
4{5 static void Main()6 {7 int day→ 2 = 2; //@day=6, 98 string label;switch (day)
10switch (day2)11{12 case 1:13 case 2:label ← weekday
11{12 case 1:13 case 2:14 case 3:15 case 4:16 case 5:17 label→ weekday = "weekday";18 break;19 case 6:Console.WriteLine($"day={day}");
28 Console.WriteLine($"day={day2}");29 Console.WriteLine($"label={labelweekday}");30}outputday=2 label=weekday
day ← 6
4{5 static void Main()6 {7 int day→ 6 = 6;8 string label;switch (day)
10switch (day6)11{12 case 1:13 case 2:label ← weekend
18 break;19case 6:20case 7:21 label→ weekend = "weekend";22 break;23default:Console.WriteLine($"day={day}");
28 Console.WriteLine($"day={day6}");29 Console.WriteLine($"label={labelweekend}");30}outputday=6 label=weekend
day ← 9
4{5 static void Main()6 {7 int day→ 9 = 9;8 string label;switch (day)
10switch (day9)11{12 case 1:13 case 2:label ← invalid
22 break;23 default:24 label→ invalid = "invalid";25 break;26}Console.WriteLine($"day={day}");
28 Console.WriteLine($"day={day9}");29 Console.WriteLine($"label={labelinvalid}");30}outputday=9 label=invalid
Match the Day
daystarts at2.- The switch checks the grouped cases.
case 2is in the weekday group.labelbecomesweekday. | Day | Case group | Label | | --- | --- | --- | |2|1through5|weekday| |6|6or7|weekend| |9|default|invalid|
Exercise: SwitchStatement.cs
Use switch cases to label a day as weekday, weekend, or invalid