Summary - Conditionals
Combine if, switch and pattern matching to write a day-of-week app.
Summary - Conditionals
In this group you learned if, else if, switch, switch expressions and the ternary operator. Now you will combine them to write a day-of-week app.
Across two exercises you will first produce the day name with a switch expression, then decide weekday or weekend with if/else. Each tool reads best in its own spot.
Exercise Produce the day name with a switch expression
Declare a day variable with the value 4. Use a switch expression to produce name: 1 => "monday", 2 => "tuesday", 3 => "wednesday", 4 => "thursday", _ => "?". Print name with Console.WriteLine.
Show example solution
Write string name = day switch { 1 => "monday", 2 => "tuesday", 3 => "wednesday", 4 => "thursday", _ => "?" };
Example solution:
using System;
class Program
{
static void Main()
{
int day = 4;
string name = day switch { 1 => "monday", 2 => "tuesday", 3 => "wednesday", 4 => "thursday", _ => "?" };
Console.WriteLine(name);
}
}
Exercise Weekday or weekend with if/else
Declare a day variable with the value 6. Use if to check day == 6 || day == 7; when it holds print "weekend" with Console.WriteLine, otherwise print "weekday" in the else branch.
Show example solution
Write if (day == 6 || day == 7) { Console.WriteLine("weekend"); } else { Console.WriteLine("weekday"); }
Example solution:
using System;
class Program
{
static void Main()
{
int day = 6;
if (day == 6 || day == 7)
{
Console.WriteLine("weekend");
}
else
{
Console.WriteLine("weekday");
}
}
}
The conditionals side by side
You now know five conditional tools: if, else if, switch, switch expressions and the ternary. Which one to pick depends on the context.
For a simple two-way pick the ternary is shortest; for two or three branches an if/else if chain; for many equality checks a switch or switch expression reads best. Prefer explicit branches over nested ternaries.
Test yourself
-
In a switch expression, which one means 'all other cases'?
var label = day switch { 1 => "one", _ => "?" };- _
- default
- *
- else
Show answer
_ — Correct. _ (discard) catches all other cases.
-
Weekend with if/else
int day = 6; if (day == 6 || day == 7) { Console.WriteLine("____"); } else { Console.WriteLine("weekday"); }Show answer
int day = 6; if (day == 6 || day == 7) { Console.WriteLine("weekend"); } else { Console.WriteLine("weekday"); }