Why chain conditions
An if/else pair handles two outcomes. When there are three or more, you add else if branches between the if and the final else. The result is one chain that picks exactly one outcome.
string language = "Python";
if (language == "JavaScript") {
Console.WriteLine("It's super popular!");
} else if (language == "Python") {
Console.WriteLine("It's so simple!");
} else if (language == "Java") {
Console.WriteLine("It's pretty hardcore!");
} else {
Console.WriteLine("It's exotic!");
}
How the chain is evaluated
C# checks the conditions from top to bottom and stops at the first one that is true:
language == "JavaScript"is false, so the program moves on.language == "Python"is true, so it runs that block and printsIt's so simple!.- The rest of the chain is skipped, and the remaining conditions aren't even evaluated.
If none of the conditions is true, the final else runs. With language set to "Go", the output would be It's exotic!. The else is optional. Without it, a value that matches nothing simply runs no branch.
Order matters
Because the first true condition wins, a later branch can rely on every earlier condition having failed. That lets you write shorter conditions. Consider grading:
int score = 85;
if (score >= 90) {
Console.WriteLine("A");
} else if (score >= 80) {
Console.WriteLine("B");
} else {
Console.WriteLine("C or lower");
}
The second branch says only score >= 80. It doesn't need score < 90, because a score of 90 or more was already handled by the first branch. Output: B.
The same idea breaks if you reverse the order. Testing score >= 80 first would catch 95 as well, and the "A" branch would never run.
A chain is not a list of separate ifs
These two pieces of code behave differently:
int n = 10;
if (n > 5) { Console.WriteLine("big"); }
else if (n > 2) { Console.WriteLine("medium"); }
// prints: big
if (n > 5) { Console.WriteLine("big"); }
if (n > 2) { Console.WriteLine("medium"); }
// prints: big, then medium
With else if, the second test only happens when the first one failed. With two separate if statements, both tests always happen.
Combining a chain with other operators
Each condition in a chain can be as complex as you need, using &&, || and !. When a chain starts to compare one variable against many fixed values, as the language example does, C# offers a switch statement that expresses the same idea more compactly. For ranges like the grades below, a chain of else if branches is the natural choice.
Only one branch of a chain ever runs, and every branch is optional except the first if. A chain without a final else can end up running nothing at all, which is sometimes exactly what you want.
Common mistakes
- Writing
elseiforelif. In C# it is two words:else if. - Putting a condition on the last
else. The finalelsenever takes one. It covers whatever is left. - Wrong order of ranges. Put the narrowest or highest check first when later conditions depend on earlier ones failing.
- Using
=instead of==.if (grade = 5)doesn't compile for anint, because an assignment isn't a boolean. Use==to compare. - Boundary values. "Up to 7" includes 7, so the test is
<= 7, not< 7. Check the value at each border. - Forgetting the braces. C# allows a single statement without braces, but the lesson keeps every branch in braces, and so should you. It prevents mistakes when you add a second line later.
The exercise, step by step
The code starts with int grade = 8;. The task is to print a message for each range of grades:
| Grade | Message |
|---|---|
| below 5 | Failed the test |
| 5 to 7 | Passed the test |
| 8 to 9 | Good Job |
| above 9 | Perfect |
- Start with the failing grades.
if (grade < 5)prints"Failed the test". Handling this first means later branches don't have to worry about grades below 5. - Add the passing range.
else if (grade <= 7)prints"Passed the test". It only runs whengradeis 5 or higher, since the first test already failed. - Add the next range.
else if (grade <= 9)prints"Good Job". It needs no lower bound, because grades 7 and below were caught earlier. - Finish with
else. It prints"Perfect"for everything above 9.
int grade = 8;
if (grade < 5) {
Console.WriteLine("Failed the test");
} else if (grade <= 7) {
Console.WriteLine("Passed the test");
} else if (grade <= 9) {
Console.WriteLine("Good Job");
} else {
Console.WriteLine("Perfect");
}
With grade = 8: 8 < 5 is false, 8 <= 7 is false, 8 <= 9 is true. The output is:
Good Job
Good grades to test are the borders: 4 gives Failed the test, 5 and 7 give Passed the test, 9 gives Good Job, and 10 gives Perfect.
Key takeaways
- A chain is written
if, then any number ofelse if, then an optionalelse. - Conditions are checked from top to bottom, and only the first true branch runs.
- Order your branches so later conditions can rely on earlier ones having failed.
- Test the values at the borders of each range.