Start learning free

LESSON 65 OF 347 · CONDITIONAL STATEMENTS

If Statements in C#: Making Decisions with if and else

Lesson Read the full explanation

TL ; DR:

  • if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

    bool isRainy = true;
    if(isRainy) {
        Console.WriteLine("I bring an umbrella");
    }
    



Full lesson:

As humans, we often make decisions based on conditions. For example, we might go through these decision-making processes during a day:

If it's rainy:
  I bring an umbrella

If I'm hungry:
  I have breakfast
  
I I'm tired:
  I take a nap

We can also tell the computer to make decisions like these in our programs.


If Statements:

if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

if(conditions) {
    // instructions
}

The keyword if tells C# to execute the code inside the curly braces (where we have our C# comment) only if the conditions defined in the parentheses are met.


Boolean conditions:

The conditions inside if statements are known as Boolean conditions and they may only be true or false.

If the boolean condition evaluates to true, the program executes the statements inside curly braces. If it evaluates to false, the statements will not execute.

If you check our example, you'll see that all the conditions there (it's rainy, I'm hungry and I'm tired) are Boolean conditions.

Let's turn those decisions into working code using if statements:

bool isRainy = true;
if(isRainy) {
    Console.WriteLine("I bring an umbrella");
}

The code above prints "I bring an umbrella" since the condition in the parentheses evaluates to true

But this code:

bool amHungry = false;
if(amHungry) {
    Console.WriteLine("I have breakfast");
}

prints nothing since amHungry evaluates to false.


Assignment
Follow the Coding Tutorial and let's practice with if statements!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    C# · CONDITIONAL STATEMENTS

    If Statements in C#, explained

    Programs that decide

    People make decisions from conditions all day: if it is raining, bring an umbrella; if you are hungry, eat. An if statement lets a C# program do the same. It runs a block of code only when a condition holds.

    bool isRainy = true;
    
    if (isRainy) {
        Console.WriteLine("I bring an umbrella");
    }
    

    This prints I bring an umbrella. With isRainy set to false it prints nothing, and the program moves on to whatever comes after the closing brace.

    The syntax

    if (condition) {
        // runs only when the condition is true
    }
    

    The condition goes inside parentheses, and the code to run goes inside curly braces. Everything between the braces is the block. If the condition is false, C# skips the whole block.

    Boolean conditions

    The condition must be a bool: a value that is either true or false. It can be a bool variable, as above, or the result of a comparison:

    int age = 20;
    
    if (age >= 18) {
        Console.WriteLine("Adult");
    }
    

    The comparison operators are == (equal), != (not equal), <, >, <= and >=. Each produces a bool.

    When a variable is already a bool, use it directly. Writing if (isRainy == true) works but only repeats what if (isRainy) says.

    Adding else

    An else block runs when the condition is false, so the program responds either way:

    bool amHungry = false;
    
    if (amHungry) {
        Console.WriteLine("I have breakfast");
    } else {
        Console.WriteLine("I skip breakfast");
    }
    

    Here amHungry is false, so the program prints I skip breakfast. Exactly one of the two blocks runs. An else has no condition of its own: it covers every case that the if did not.

    More than two outcomes

    When there are more than two cases, chain them with else if. C# tests the conditions from top to bottom and runs the first block whose condition is true:

    int score = 75;
    
    if (score >= 90) {
        Console.WriteLine("A");
    } else if (score >= 70) {
        Console.WriteLine("B");
    } else {
        Console.WriteLine("C");
    }
    

    This prints B. The first condition is false, the second is true, and the final else is skipped. Once one block has run, the rest of the chain is ignored.

    The exercise, step by step

    The lesson starts with bool passed = true; and builds a small program on it.

    1. Write the if. The condition is just passed, in parentheses, followed by { to open the block.
    2. Print the success message. Inside the block, Console.WriteLine("Passed the test"); runs only when passed is true. WriteLine ends the line, so each message gets its own line.
    3. Add the else. Write } else { on one line, which closes the if block and opens the else block. Print "Failed" inside and close with }.
    bool passed = true;
    if (passed) {
        Console.WriteLine("Passed the test");
    } else {
        Console.WriteLine("Failed");
    }
    

    Since passed is true, the program prints Passed the test. If you change the first line to bool passed = false; it prints Failed, which is a good way to check both branches.

    C# details to know

    • Only a bool works as a condition. C# does not treat numbers or strings as true or false. if (1) and if (name) are compile errors, unlike in some other languages.
    • One equals sign assigns, two compare. if (x = 5) is an error for an int, and if (x == 5) is the check you want. With a bool variable flag, the slip if (flag = true) does compile. It sets flag to true and always runs the block, and the compiler warns about it.
    • Keep the braces. C# lets you leave them off for a single statement, but only that one statement belongs to the if. A second indented line would run every time. Always writing braces avoids that trap.
    • No semicolon after the condition. if (passed); ends the statement immediately, so the block after it is not controlled by the condition.

    Common mistakes

    • Forgetting the parentheses around the condition. C# requires them.
    • Writing Else or If with a capital letter. Keywords are lowercase.
    • Putting a condition on else. else (x > 3) is invalid. To test another condition, use else if.
    • Using console.writeline. The name is Console.WriteLine, with capitals.

    Key takeaways

    • if (condition) { ... } runs the block only when the condition is true.
    • The condition must be a bool, such as a variable or a comparison.
    • else covers the case where the condition is false.
    • Use == to compare and = to assign.
    • Always use curly braces, even for one statement.
    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