If/Else and Switch Expressions
Branching in C#, from classic if/else chains to the more concise switch expression syntax.
2 min read
C#'s if/else looks like what you'd expect from a C-family language:
int age = 20;
if (age < 13)
{
Console.WriteLine("Child");
}
else if (age < 20)
{
Console.WriteLine("Teenager");
}
else
{
Console.WriteLine("Adult");
}One strictness worth flagging: the condition inside if (...) must be a bool. Unlike JavaScript, C# won't let you write if (someNumber) and have it "just work" via truthiness — you'd write if (someNumber != 0) explicitly. This is deliberate; it removes a whole class of "was that supposed to be a comparison?" bugs.
Classic switch statements
string day = "Mon";
switch (day)
{
case "Mon":
case "Tue":
case "Wed":
case "Thu":
case "Fri":
Console.WriteLine("Weekday");
break;
case "Sat":
case "Sun":
Console.WriteLine("Weekend");
break;
default:
Console.WriteLine("Unknown");
break;
}Each case needs a break (or return) — C# doesn't fall through to the next case silently the way C does, and the compiler will actually reject a case with executable code that falls through unintentionally. Stacking cases like case "Mon": case "Tue": with no code in between is fine and common, as shown above.
Switch expressions: the modern, concise form
Since C# 8, switch can also be an expression that produces a value directly, instead of a statement full of breaks:
string category = day switch
{
"Mon" or "Tue" or "Wed" or "Thu" or "Fri" => "Weekday",
"Sat" or "Sun" => "Weekend",
_ => "Unknown",
};This is shorter, avoids repeated break statements, and reads closer to a lookup table than a sequence of instructions. _ is the discard pattern — it matches anything not already handled, playing the same role default does in a switch statement.
Choosing between them
Reach for a switch expression when you're computing a single value from one input — it's compact and the compiler will warn you if you miss a case on an enum. Reach for if/else or a switch statement when each branch needs to run multiple statements or has side effects beyond producing a value. Both compile down to similar logic; this is purely a readability choice.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.