Conditionals
Conditionals decide which code actually runs. C# gives you two main tools for this: if/else for open-ended branching logic, and switch for checking one value against a fixed set of possibilities.
if, else if, else
Conditions are checked top to bottom, and the first one that's true wins — the rest are skipped entirely:
int score = 82;
string grade;
if (score >= 90)
{
grade = "A";
}
else if (score >= 80)
{
grade = "B";
}
else if (score >= 70)
{
grade = "C";
}
else
{
grade = "F";
}
Console.WriteLine($"Score: {score} -> Grade: {grade}");
Score: 82 -> Grade: B
82 fails the >= 90 check, passes >= 80, and stops there — it never even reaches the >= 70 check. Order matters: if the branches were listed smallest-to-largest instead, every score of 70 or above would incorrectly match the first one it hit.
switch statement
When you're comparing one value against several exact possibilities, a chain of if/else if works but reads repetitively. switch was built for exactly this shape of problem:
int dayNumber = 3;
string dayName;
switch (dayNumber)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Unknown";
break;
}
Console.WriteLine(dayName);
Wednesday
Each case needs a break (or another way of exiting, like return) — unlike some languages, C# won't let execution silently fall through from one case into the next by accident; leaving out break where it's needed is a compile error, not a runtime surprise.
switch expressions
Modern C# also has a switch expression — a more compact form that directly produces a value instead of assigning inside every branch. It reads less like a control-flow statement and more like a lookup table:
int dayNumber = 6;
string dayType = dayNumber switch
{
1 or 2 or 3 or 4 or 5 => "Weekday",
6 or 7 => "Weekend",
_ => "Invalid"
};
Console.WriteLine(dayType);
Weekend
The _ at the end is a discard pattern — it matches anything not already covered above it, playing the same role default plays in a classic switch statement. Leave it out and feed the expression a value that matches nothing, and it throws an exception at runtime rather than silently producing nothing.
switch statement when each branch needs to run multiple lines of logic or side effects; reach for the switch expression when what you really want is "map this input to that output value" in one line, since it's shorter and the compiler can check you've covered every case.