Welcome back! Yesterday your code learned to compare and combine things with operators. Today we finally use all those true/false answers for something useful: making decisions. This is the day your program grows a tiny brain. ๐ง
Up to now, your code has been a straight line โ it runs from top to bottom like a very obedient intern. Today we teach it to fork the road.
1. The if Statement โ The Bouncer at the Door
An if statement is a bouncer with a clipboard. It checks a condition (a bool expression), and if it's true, it lets the code inside the { } run. If it's false, that code gets skipped entirely.
int age = 20;
if (age >= 18)
{
Console.WriteLine("Welcome in!");
}
Read it out loud: "IF age is greater-than-or-equal-to 18, print the welcome message."
Three things to notice:
- The condition goes in parentheses
( ). - The code to run goes in curly braces
{ }. - No semicolon after
if (...)โ the braces are the ending.
2. else โ The Backup Plan
What if the bouncer says no? You probably want to do something else. Enter else:
int age = 15;
if (age >= 18)
{
Console.WriteLine("Welcome in!");
}
else
{
Console.WriteLine("Sorry, come back in a few years.");
}
Exactly one of those two blocks will run. Never both, never neither.
3. else if โ The Menu of Options
When you have more than two paths, chain else if blocks:
int score = 73;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else if (score >= 60)
{
Console.WriteLine("Grade: D");
}
else
{
Console.WriteLine("Grade: F");
}
C# checks the conditions top-to-bottom and runs the first one that's true. Everything after that is skipped. That's why you put the strictest condition (>= 90) first โ if you reversed the order, everyone would get an A.
4. Nesting (Use Sparingly!)
You can put an if inside another if:
if (isLoggedIn)
{
if (isAdmin)
{
Console.WriteLine("Welcome, boss!");
}
else
{
Console.WriteLine("Welcome, user!");
}
}
But don't go crazy. Three levels deep and your code starts to look like a staircase. Usually you can flatten it by combining conditions with &&:
if (isLoggedIn && isAdmin)
{
Console.WriteLine("Welcome, boss!");
}
else if (isLoggedIn)
{
Console.WriteLine("Welcome, user!");
}
Much friendlier to read.
5. The switch Statement โ A Cleaner Menu
When you're comparing one variable against many specific values, a long else if chain gets ugly fast. That's what switch is for:
string day = "Wednesday";
switch (day)
{
case "Monday":
Console.WriteLine("Fresh start!");
break;
case "Wednesday":
Console.WriteLine("Hump day.");
break;
case "Friday":
Console.WriteLine("Almost weekend!");
break;
default:
Console.WriteLine("Just another day.");
break;
}
Rules of the road:
- Each
caselists one specific value to match. break;is mandatory โ it tells C# to jump out of the switch. Forget it and the compiler yells at you.default:runs if no case matched. Think of it as theelseof switches.
You can also group cases that share the same code:
switch (day)
{
case "Saturday":
case "Sunday":
Console.WriteLine("Weekend!");
break;
default:
Console.WriteLine("Weekday.");
break;
}
6. Switch Expressions โ The Modern, Shiny Version
C# 8 (and beyond) gave us a much tighter syntax called a switch expression. It returns a value instead of running statements:
string day = "Wednesday";
string mood = day switch
{
"Monday" => "Fresh start!",
"Wednesday" => "Hump day.",
"Friday" => "Almost weekend!",
"Saturday" or "Sunday" => "Weekend!",
_ => "Just another day."
};
Console.WriteLine(mood);
Notice:
- No
case, nobreak, no{ }around each arm. =>("goes to") replaces the:._(underscore) is the discard โ it's thedefaultof switch expressions.- Arms are separated by commas.
When you're picking a value based on input, prefer switch expressions. They're shorter, safer, and the compiler will warn you if you forget a case. See switch expression docs for the full story.
7. if vs switch โ Which Do I Use?
| Situation | Use |
|---|---|
Checking a range (score >= 90) |
if / else if |
Combining multiple conditions (a && b) |
if / else if |
| Matching one variable to specific values | switch |
| Producing a value from a match | switch expression |
Rule of thumb: ranges and combos โ if. Specific values โ switch.
8. Your Homework: A Traffic Light
Ask the user what color the traffic light is, then tell them what to do. Use a switch expression.
Console.Write("Traffic light color (red/yellow/green): ");
string color = Console.ReadLine()?.ToLower() ?? "";
string action = color switch
{
"red" => "Stop!",
"yellow" => "Slow down.",
"green" => "Go!",
_ => "That's not a traffic light color..."
};
Console.WriteLine(action);
Two tiny new things hiding in there:
.ToLower()converts the user's input to lowercase so"Red","RED", and"red"all match.?.is the null-conditional operator โ ifConsole.ReadLine()returnsnull, the whole thing short-circuits safely. The?? ""says "if we did get null, use an empty string instead." We'll cover null properly in a later day, but get used to seeing these two.
Bonus challenge: also handle "flashing" as a special case that prints "Proceed with caution."
Summary of Day 4
if/else/else iflet your code pick different paths based onboolconditions.- Conditions go in
( ), code bodies go in{ }. else ifchains are checked top-to-bottom โ first match wins.switchstatements are cleaner when matching one variable against many values. Everycaseneeds abreak.- Switch expressions (
x switch { ... }) are the modern way to produce a value from a match. Use_for the default. - Rule of thumb: ranges/combos โ
if. Specific values โswitch.
Tomorrow: we'll talk about Loops โ for, while, and foreach. Because typing Console.WriteLine 100 times is no way to live. ๐
See you on Day 5!