Start learning free

LESSON 79 OF 347 · CONDITIONAL STATEMENTS

Chaining Conditionals in C#: if, else if and else

Lesson Read the full explanation

Sometimes we can have more than two possible scenarios which need a different code to be ran. We can add else if statements to allow for as many outcomes as we want:

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!");
}

In the example above, language == "JavaScript" evaluates to false, so we move on and enter the following else if.

There, language == "Python" evaluates to true, so we execute what's inside that block and print "It's so simple!".

The rest of the conditions are not evaluated.

In case none of the conditions evaluates to true, then the code in the final else statement would execute. For example, if language was "Go", the program would have printed "It's exotic!"


Assignment
Follow the Coding Tutorial and let's write some chained conditionals.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    C# · CONDITIONAL STATEMENTS

    Chaining Conditionals in C#, explained

    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:

    1. language == "JavaScript" is false, so the program moves on.
    2. language == "Python" is true, so it runs that block and prints It's so simple!.
    3. 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 elseif or elif. In C# it is two words: else if.
    • Putting a condition on the last else. The final else never 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 an int, 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:

    GradeMessage
    below 5Failed the test
    5 to 7Passed the test
    8 to 9Good Job
    above 9Perfect
    1. 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.
    2. Add the passing range. else if (grade <= 7) prints "Passed the test". It only runs when grade is 5 or higher, since the first test already failed.
    3. Add the next range. else if (grade <= 9) prints "Good Job". It needs no lower bound, because grades 7 and below were caught earlier.
    4. 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 of else if, then an optional else.
    • 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.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free