if / else if / else (C#)
The basic syntax for conditional branching. Use if to define a block that runs when a condition is true, else if to add extra conditions, and else to handle the case where none of the conditions match. In C#, the condition expression must be of type bool — you cannot pass an integer directly.
Syntax
if (condition) {
// Executes when the condition is true.
}
// Syntax with else if and else.
if (condition1) {
// Executes when condition1 is true.
} else if (condition2) {
// Executes when condition1 is false and condition2 is true.
} else {
// Executes when all conditions are false.
}
// Nested conditional branching.
if (conditionA) {
if (conditionB) {
// Executes when both conditionA and conditionB are true.
}
}
// Conditional operator (ternary operator). Use it for simple value selection.
var result = condition ? valueIfTrue : valueIfFalse;
Common Operators Used in Conditions
| Operator | Meaning | Example |
|---|---|---|
| == | Equal to. | hp == 0 |
| != | Not equal to. | level != 1 |
| > | Greater than. | score > 100 |
| >= | Greater than or equal to. | score >= 100 |
| < | Less than. | hp < 0 |
| <= | Less than or equal to. | hp <= 0 |
| && | And (logical AND). If the left side is false, the right side is not evaluated (short-circuit evaluation). | hp > 0 && isAlive |
| || | Or (logical OR). If the left side is true, the right side is not evaluated (short-circuit evaluation). | isActive || isElite |
| ! | Not (logical NOT). | !isDisabled |
Sample Code
IfElseBasic.cs
using System;
class IfElseBasic {
static void Main() {
string name = "item_x";
int score = 850;
if (score >= 1000) {
Console.WriteLine(name + " is rank_S.");
} else if (score >= 500) {
Console.WriteLine(name + " is rank_A."); // This branch executes.
} else {
Console.WriteLine(name + " is rank_B.");
}
// Passing an int directly causes a compile error.
// if (score) { } // Error: cannot implicitly convert int to bool.
bool isActive = true;
if (isActive) {
Console.WriteLine(name + " is active."); // This branch executes.
}
bool isActive2 = true;
bool hasOption = false;
if (isActive2) {
if (hasOption) {
Console.WriteLine(name + " has option enabled.");
} else {
Console.WriteLine(name + " is active but has no option."); // This branch executes.
}
} else {
Console.WriteLine(name + " is inactive.");
}
// Also known as a guard clause.
// Rejecting invalid values early reduces nesting depth.
Console.WriteLine(GetStatusMessage("item_a", -1));
Console.WriteLine(GetStatusMessage("item_b", 15000));
Console.WriteLine(GetStatusMessage("item_c", 1500));
// The conditional operator is more readable for simple value selection.
int hp = 0;
string status = hp > 0 ? "active" : "inactive";
Console.WriteLine("item_c status: " + status);
// Use if/else when the logic spans multiple lines or involves nesting.
}
// A method that avoids deep nesting by using early return.
static string GetStatusMessage(string name, int score) {
if (score < 0) {
return name + " has an invalid score."; // Reject the invalid value early.
}
if (score >= 10000) {
return name + " is rank_S.";
}
if (score >= 5000) {
return name + " is rank_A.";
}
return name + " is rank_B."; // Fallback when no condition matches.
}
}
This produces the following output:
dotnet script IfElseBasic.cs item_x is rank_A. item_x is active. item_x is active but has no option. item_a has an invalid score. item_b is rank_S. item_c is rank_B. item_c status: inactive
Common Mistakes
Passing an integer directly as a condition
In C/C++, you can write if (count) with an integer directly as the condition, but this causes a compile error in C#. The if statement in C# accepts only bool, so you must use a comparison operator such as if (count != 0).
int count = 5;
// Compile error: Cannot implicitly convert type 'int' to 'bool'
// if (count) { }
// Correct: use a comparison operator to produce a bool.
if (count != 0) {
Console.WriteLine("count is not 0.");
}
Unreachable code due to else if condition ordering
When chaining else if, placing a broader condition first prevents narrower conditions from ever being reached. Write narrower conditions first.
int score = 15000;
// Unintended result: score >= 500 matches first, so >= 1000 is never reached.
if (score >= 500) {
Console.WriteLine("rank_A");
} else if (score >= 1000) {
Console.WriteLine("rank_S"); // Never reached.
}
// Correct order: write the narrower condition (>= 1000) first.
if (score >= 1000) {
Console.WriteLine("rank_S");
} else if (score >= 500) {
Console.WriteLine("rank_A");
}
Overview
In C#, only bool (or bool?) is allowed as a condition expression. Unlike C or Java, passing an integer such as 0 or 1 directly to if causes a compile error. Constructs like if (count) are not valid — you must produce a bool via a comparison, such as if (count != 0).
For simple branching that only selects a value, the conditional operator (condition ? true : false) is more concise. However, when the logic spans multiple lines or involves nesting, if / else is more readable. Forcing the conditional operator into complex cases tends to produce hard-to-read code, so choose based on the situation.
When nesting becomes deep, using early return (guard clauses) to reject conditions upfront leads to cleaner code. For multi-way branching, switch statements and switch expressions are also effective. For branching by type, see is / as / Pattern Matching.
If you find any errors or copyright issues, please contact us.