Conditional Statements
C# conditionals work like Java's with one powerful addition: the switch expression, which is concise, exhaustive, and eliminates fall-through bugs.
int mark = 74;
if (mark >= 80)
Console.WriteLine("Distinction");
else if (mark >= 60)
Console.WriteLine("Merit");
else if (mark >= 50)
Console.WriteLine("Pass");
else
Console.WriteLine("Not yet competent");
Switch Expression (C# 8+)
The switch expression is concise, exhaustive (the compiler warns if a case is missing), and has no fall-through. It returns a value directly.
// Switch expression — cleaner than switch statement
string result = mark switch {
>= 80 => "Distinction",
>= 60 => "Merit",
>= 50 => "Pass",
_ => "Not yet competent" // _ is the catch-all
};
Console.WriteLine(result);
// Traditional switch statement (still used with legacy code):
string day = "Wednesday";
switch (day) {
case "Monday": Console.WriteLine("Java class"); break;
case "Wednesday": Console.WriteLine("Career dev"); break;
case "Friday": Console.WriteLine("Presentations"); break;
default: Console.WriteLine("Self-study"); break;
}
Pattern Matching in Conditions
// is pattern — type check and cast in one step:
object obj = "Hello from Your IT Tutor";
if (obj is string s && s.Length > 5)
Console.WriteLine($"String of length {s.Length}: {s}");
// Switch with type patterns:
static string Describe(object o) => o switch {
int n when n > 0 => $"Positive int: {n}",
int n => $"Non-positive int: {n}",
string s => $"String: {s}",
null => "null",
_ => $"Other: {o.GetType().Name}"
};
Practice Task
Your Turn
Write a program with a hardcoded learner mark and a boolean for on-time submission. Use a switch expression to assign a grade label. Use a nested if to print an extra message if they passed but submitted late. Use a traditional switch for the day-of-week schedule.
Common Mistakes
- Forgetting the
_catch-all in a switch expression — the compiler will warn about unhandled cases. - Missing
breakin traditional switch — fall-through is silent. - Semicolon after
if(...)— creates an empty body. - Ordering conditions from least to most restrictive — a 90% would match
>= 50first and show 'Pass'.
Professional Tip
The switch expression is one of C#'s best modern features. It eliminates three entire classes of bugs: forgetting break, missing cases, and ordering issues. Use it over switch statements for new code.
Mini Quiz
What is the catch-all symbol in a C# switch expression?