C#: Conditionals
1. The if Statement
The if statement executes a code block based on the result of a boolean expression. When the condition is true, the block runs; when false, it is skipped.
int score = 85;
if (score >= 60)
{
Console.WriteLine("Passed");
}
Passed
2. The if...else Statement
Use if...else to execute one branch when the condition is true and another when it is false.
int age = 16;
if (age >= 18)
{
Console.WriteLine("Adult");
}
else
{
Console.WriteLine("Minor");
}
Minor
3. if...else if Multiple Branches
When you need to check several mutually exclusive conditions, use else if to test them in order. Only the first matching branch executes.
int score = 78;
if (score >= 90)
{
Console.WriteLine("Excellent");
}
else if (score >= 80)
{
Console.WriteLine("Good");
}
else if (score >= 60)
{
Console.WriteLine("Pass");
}
else
{
Console.WriteLine("Fail");
}
Pass
4. Nested if
if statements can be nested, but try to keep nesting to no more than two levels. Deep nesting hurts readability - consider extracting a method or using else if instead.
▶ Example
int age = 25;
bool hasTicket = true;
if (age >= 18)
{
if (hasTicket)
{
Console.WriteLine("Admitted");
}
else
{
Console.WriteLine("Ticket required");
}
}
else
{
Console.WriteLine("Too young");
}
Admitted
5. The switch Statement
A switch statement matches an expression against multiple constant values and executes the corresponding case branch. Unlike C/C++, C# does not allow fall-through; each case must end with break, return, or throw, or a compile error occurs.
▶ Example
int day = 3;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
default:
Console.WriteLine("Weekend");
break;
}
Wednesday
Multiple cases can share the same logic by listing their labels consecutively:
int month = 2;
switch (month)
{
case 12:
case 1:
case 2:
Console.WriteLine("Winter");
break;
case 3:
case 4:
case 5:
Console.WriteLine("Spring");
break;
default:
Console.WriteLine("Other season");
break;
}
Winter
Tip: In C#, if you genuinely need to jump from one case to another, you must use
goto case x; omitting break for fall-through is not allowed.
6. Switch Expressions (C# 8+)
C# 8 introduced switch expressions, which are expressions rather than statements. They return the matched result with a more concise syntax. Use _ for the default branch.
▶ Example
int code = 404;
string message = code switch
{
200 => "OK",
301 => "Moved",
404 => "Not Found",
500 => "Server Error",
_ => "Unknown"
};
Console.WriteLine(message);
Not Found
7. Pattern Matching Basics
Starting with C# 7, you can use pattern matching in conditional logic. Common forms include type patterns (is Type variable) and when guards.
▶ Example
object obj = "Hello C#";
if (obj is string s)
{
Console.WriteLine($"String length: {s.Length}");
}
else
{
Console.WriteLine("Not a string");
}
String length: 8
Use a when guard in a switch to add extra conditions:
int value = 15;
string category = value switch
{
int i when i > 100 => "Extra large",
int i when i > 10 => "Medium",
int i when i > 0 => "Small",
_ => "Invalid"
};
Console.WriteLine(category);
Medium
8. The Conditional Operator ?:
The conditional operator ?:, also known as the ternary operator, is a shorthand for if...else. The syntax is condition ? valueIfTrue : valueIfFalse, and the entire expression evaluates to the corresponding value.
▶ Example
int age = 20;
string status = age >= 18 ? "Adult" : "Minor";
Console.WriteLine(status);
Adult
Nested usage (avoid excessive nesting):
int score = 75;
string result = score >= 90 ? "A" : score >= 60 ? "B" : "C";
Console.WriteLine(result);
B
Warning: Readability drops sharply when the conditional operator is nested more than two levels deep. Use if...else if statements instead.
❓ FAQ
=> and comma-separated arms. A switch statement is a statement that does not require a return value, using case/break blocks.is and ==?== compares values for equality, while is is used for pattern matching and can check the type while declaring a variable, such as obj is string s.📖 Summary
- The if statement executes a code block based on a boolean condition
- if...else provides two-way branching; else if handles multiple mutually exclusive conditions
- Keep nested if statements to two levels or fewer for readability
- switch matches constant values; C# prohibits fall-through and requires break/return/throw
- Switch expressions (C# 8+) are a concise, value-returning alternative using
_for the default - Pattern matching uses
is Type varto check types and extract values; when guards add extra conditions - The conditional operator
?:simplifies simple two-way assignments
📝 Exercises
- Write a program that reads an integer and determines whether it is positive, negative, or zero, then outputs the result
- Use a switch expression to map a month (1-12) to its corresponding season name
- Write a program that receives an object variable, uses
ispattern matching to determine its type (int, string, or other), and outputs the type and value - Use the conditional operator to convert a numeric score to a letter grade (90+ is A, 80+ is B, 60+ is C, otherwise D), then compare readability with an if...else if version