C# If Else

An if statement lets a C# program choose whether to run a block of code. An else block gives the program an alternative path when the condition is false. This matters because real programs constantly make decisions: approve an order, show an error, calculate a discount, or stop invalid data before it spreads.

Overview: How If Else Works

C# control flow normally runs from top to bottom, one statement after another. An if statement changes that flow by evaluating a condition. If the condition evaluates to true, C# executes the statement or block attached to the if. If the condition evaluates to false, C# skips that block and continues after it, unless there is an else or else if branch to consider.

The condition in an if statement must be a bool. C# does not treat numbers, strings, objects, or collections as truthy or falsy. For example, if (count) does not compile when count is an int. You must write a real Boolean expression such as count > 0. This strict rule catches many mistakes at compile time.

An else if chain checks multiple conditions in order. C# evaluates the first condition. If it is true, that branch runs and the rest of the chain is skipped. If it is false, C# tries the next else if. The final else, if present, handles everything that did not match earlier. This means branch order matters: put more specific conditions before more general ones.

Most if statements use braces to group several statements into one block. Braces create a clear body for the branch and also introduce a local scope. Variables declared inside an if block are available only inside that block. The compiler uses this scope information while checking names, types, and definite assignment.

Under the hood, the C# compiler translates an if statement into branching instructions in Intermediate Language. The CLR runs the condition code, obtains a Boolean result, then jumps to the matching block. For ordinary application code, you should think in terms of readable branches, not machine jumps, but knowing that only one branch of an if/else if/else chain runs helps explain side effects and performance.

Syntax

bool condition = true;
bool anotherCondition = false;

if (condition)
{
    // runs when condition is true
}
else if (anotherCondition)
{
    // runs when the first condition is false and this one is true
}
else
{
    // runs when none of the previous conditions were true
}
Part Meaning
if Starts a decision. Its condition must evaluate to bool.
condition A Boolean expression, such as age >= 18 or isValid && hasPaid.
{ } Groups the statements that belong to a branch and creates a block scope.
else if Adds another condition that is checked only when earlier conditions were false.
else Optional fallback branch. It has no condition because it means all previous checks failed.

Examples

A Simple if else Decision

using System;

class Program
{
    static void Main()
    {
        int temperature = 31;

        if (temperature >= 30)
        {
            Console.WriteLine("Use extra cooling.");
        }
        else
        {
            Console.WriteLine("Standard cooling is enough.");
        }

        Console.WriteLine("Check complete.");
    }
}

Output:

Use extra cooling.
Check complete.

The condition temperature >= 30 evaluates to true, so the first block runs and the else block is skipped. After the decision is finished, execution continues with the next statement after the whole if/else.

Using else if for Ranges

using System;

class Program
{
    static void Main()
    {
        int score = 84;

        if (score >= 90)
        {
            Console.WriteLine("Grade: A");
        }
        else if (score >= 80)
        {
            Console.WriteLine("Grade: B");
        }
        else if (score >= 70)
        {
            Console.WriteLine("Grade: C");
        }
        else
        {
            Console.WriteLine("Grade: Review needed");
        }
    }
}

Output:

Grade: B

The first condition is false because 84 is not at least 90. The second condition is true, so C# prints Grade: B and skips the remaining branches. The score >= 70 condition is also true mathematically, but it is never evaluated because an earlier branch already matched.

Combining Conditions in a Real Rule

using System;

class Program
{
    static void Main()
    {
        decimal orderTotal = 62.50m;
        bool isMember = true;
        bool couponApplied = false;

        if ((isMember || couponApplied) && orderTotal >= 50m)
        {
            Console.WriteLine("Discount approved");
            Console.WriteLine($"Discounted total: {orderTotal * 0.90m:0.00}");
        }
        else
        {
            Console.WriteLine("No discount");
        }
    }
}

Output:

Discount approved
Discounted total: 56.25

This condition has two parts. The customer must be a member or have a coupon, and the order total must be at least 50m. Parentheses make the intended grouping clear. The numeric format 0.00 prints two decimal places without depending on the machine's currency culture.

Nested if Statements

using System;

class Program
{
    static void Main()
    {
        bool accountExists = true;
        bool passwordMatches = false;

        if (accountExists)
        {
            if (passwordMatches)
            {
                Console.WriteLine("Signed in");
            }
            else
            {
                Console.WriteLine("Incorrect password");
            }
        }
        else
        {
            Console.WriteLine("Create an account first");
        }
    }
}

Output:

Incorrect password

The outer if checks whether there is an account. Only when that is true does the inner if check the password. Nesting is useful when one decision depends on another, but deep nesting can become hard to read, so use it carefully.

How If Else Works Step by Step

  1. The compiler checks that the expression inside parentheses has type bool.
  2. It checks each branch body for normal C# rules: valid variables, valid types, reachable code, and definite assignment.
  3. It emits branching instructions so the runtime can jump around blocks that should not execute.
  4. At runtime, the condition is evaluated. Logical operators such as && and || may short-circuit, so the right side may be skipped.
  5. If the result is true, the matching branch runs. In an else if chain, all later branches are skipped after the first match.
  6. Variables declared inside a branch are removed from scope when that branch ends, even though the CLR may optimize their actual storage.

Short-circuiting is especially important in conditions that protect later operations. A condition such as name != null && name.Length > 0 is safe because the length check runs only when name is not null. If the left side is false, the whole && expression is already false.

Common Mistakes

Using a Non-Boolean Condition

int count = 3;
if (count)
{
    Console.WriteLine("Items found");
}

This does not compile because count is an int, not a bool. Compare it to a number so the condition has a clear true-or-false meaning.

int count = 3;
if (count > 0)
{
    Console.WriteLine("Items found");
}

Output:

Items found

Forgetting Braces Around Multiple Statements

int balance = 5;
if (balance >= 10)
    Console.WriteLine("Purchase approved");
    Console.WriteLine("Receipt printed");

Output:

Receipt printed

This compiles, but only the first Console.WriteLine belongs to the if. The second line always runs. Braces make the intended branch body explicit.

int balance = 5;
if (balance >= 10)
{
    Console.WriteLine("Purchase approved");
    Console.WriteLine("Receipt printed");
}
else
{
    Console.WriteLine("Insufficient balance");
}

Output:

Insufficient balance

Putting Conditions in the Wrong Order

int score = 95;
if (score >= 60)
{
    Console.WriteLine("Pass");
}
else if (score >= 90)
{
    Console.WriteLine("Excellent");
}

Output:

Pass

The Excellent branch is unreachable for high scores because score >= 60 matches first. Put the most specific range first.

int score = 95;
if (score >= 90)
{
    Console.WriteLine("Excellent");
}
else if (score >= 60)
{
    Console.WriteLine("Pass");
}

Output:

Excellent

Best Practices

  • Use braces even for single-statement branches. They prevent accidental always-run lines when the branch grows later.
  • Keep conditions readable. Store complex checks in well-named bool variables such as isEligible or hasEnoughCredit.
  • Order else if chains from most specific to most general when ranges overlap.
  • Use else for a real fallback, especially when invalid or unexpected input should be handled explicitly.
  • Avoid deeply nested decisions when an early return, helper method, or separate validation step would make the flow clearer.
  • Use && and || for normal conditions so C# can short-circuit safely.
  • Do not compare plain Booleans to true unless it genuinely improves clarity; if (isReady) is idiomatic.
  • When comparing strings in conditions, choose the comparison intentionally if case or culture matters.

Practice Exercises

  1. Create an int age variable. Print Child when it is below 13, Teen when it is below 20, and Adult otherwise.
  2. Write a program with decimal cartTotal and bool hasCoupon. Print whether a customer gets free shipping when the total is at least 75m or a coupon is present.
  3. Create string? username. Use an if statement that safely prints Welcome only when the name is not null and has at least three characters.

Summary

  • if runs a branch only when its Boolean condition is true.
  • else if checks another condition only after previous conditions fail.
  • else is the optional fallback for all unmatched cases.
  • C# conditions must be bool; numbers and strings are not truthy or falsy.
  • Only the first matching branch in an if/else if/else chain runs.
  • Braces make branch bodies clear and create a local scope.
  • Readable condition order and well-named Boolean variables make decision code easier to maintain.