7 min read

The C# If Else Statement: Syntax, Examples, and Best Practices

Article Summary

Using a C# if else statement lets you control which code runs based on whether a condition is true or false. This article covers basic syntax, boolean logic, embedded if statements, and the && and || operators. You'll gain the skills to write clean, logical conditional code in C#.

The if else statement in C# lets you execute different blocks of code based on whether a condition is true or false. You’ll use it as one of the most fundamental tools for controlling program flow in any C-derived language.

if (condition)
{
 // code runs when condition is true
}
else
{
 // code runs when condition is false
}

Conditional statements are fundamental to every programming language, and you’ll find them in virtually any application with a significant amount of code. That’s why understanding the C# if-else structure is essential. 

The trickiest part isn’t the syntax, but grasping the logic behind evaluation order. Once that clicks, you’ll always know exactly which branch of your if-else statement will execute.

This article covers the basic if statement, else clauses, else if chains, nested conditionals, and logical operators. 

C# if else syntax at a glance

Basic if statement:

if (condition)
{
 // executes when condition is true
}


If-else statement:

if (condition)
{
 // executes when condition is true
}
else
{
 // executes when condition is false
}


If-else if-else statement:

if (condition1)
{
 // executes when condition1 is true
}
else if (condition2)
{
 // executes when condition2 is true
}
else
{
 // executes when all conditions are false
}

Keep this reference handy while coding. The condition always goes inside parentheses, and the code blocks are enclosed in curly braces.

The basic if statement in C#

The if statement tests a specific condition. If the condition returns the boolean true, the code within the braces executes. Let’s start with a simple example:

using System;

public class Program
{
    public static void Main()
    {
        bool isLoggedIn = true; // Try changing this to false.

        if (isLoggedIn)
        {
            Console.Write("Welcome back!");
        }
    }
}

When isLoggedIn is true, the message prints. When it’s false, nothing happens and the program continues to the next line after the if block.

How boolean conditions work

Every condition in an if statement must evaluate to either true or false. A boolean variable works directly as a condition, but you can also use any expression that returns a boolean result. This includes comparisons, method calls that return bool, and combinations of logical operators.

using System;

public class Program
{
    public static void Main()
    {
        bool myCondition = false;

        Console.WriteLine($"myCondition: {myCondition}");
        Console.WriteLine($"!myCondition: {!myCondition}");

        if (!myCondition)
        {
            Console.WriteLine("The if statement executes because !myCondition is true.");
        }
    }
}

Notice the exclamation mark before myCondition. This negation operator flips the value, so !myCondition means “if myCondition is NOT true.” Since myCondition is false, !myCondition evaluates to true, and the block runs. Without the exclamation mark, if (myCondition) would check whether the variable is true, and in this case, the block would be skipped.

Using comparison operators

You’ll often compare values rather than using boolean variables directly. Here are the comparison operators available in C#:

  • == checks if two values are equal.
  • != checks if two values are not equal.
  • < checks if the left value is less than the right.
  • > checks if the left value is greater than the right.
  • <= checks if the left value is less than or equal to the right.
  • >= checks if the left value is greater than or equal to the right.
using System;

public class Program
{
    public static void Main()
    {
        int userAge = 25; // Try changing this to 16 or 18.

        if (userAge >= 18)
        {
            Console.WriteLine("User is an adult");
        }
    }
}

A common mistake is using a single equals sign (=) instead of double (==). The single equals sign assigns a value, while double equals compares values. The compiler usually throws an error if you use assignment inside a condition, unless you assign a true/false value, like if (isReady = true), which still compiles, but you’ll get a warning instead, which is easy to miss.

If you want to take your C# skills to the next level, check out the Complete C# Masterclass on Udemy, which covers everything from object-oriented programming and LINQ to building real games with Unity. With over 46 hours of content, hands-on exercises, and real-world projects, it’s the most comprehensive way to go from beginner to confident C# developer. 

Adding else to handle false conditions

The else clause provides an alternative path when your condition evaluates to false. Instead of doing nothing, you can execute different code:

using System;

public class Program
{
    public static void Main()
    {
        bool isSubscribed = false;

        if (isSubscribed)
        {
            Console.Write("Thanks for subscribing!");
        }
        else
        {
            Console.Write("Consider subscribing for updates.");
        }
    }
}

In this example, since isSubscribed is false, the else block executes and prints the subscription prompt. The else clause is optional, but it’s useful when you need to handle both outcomes explicitly.

Your variables will typically be set dynamically based on user input, database queries, or other runtime conditions. This means either branch could execute depending on the program state. 

Using else if to check multiple conditions

When you need to test more than two possibilities, use else if to create a chain of conditions. The program evaluates each condition in order and executes only the first block where the condition is true:

using System;

public class Program
{
    public static void Main()
    {
        int score = 85; // Try 95, 75, or 60 to see different grades.

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

Here’s how the evaluation works:

  1. The program checks if score is 90 or higher. If true, it prints “Grade: A” and skips all remaining conditions.
  2. If the first condition is false, it checks if score is 80 or higher.
  3. This continues down the chain until a condition is true or the else block is reached.
  4. Only one block ever executes, even if multiple conditions would be true.

When to use else if vs multiple if statements

There’s an important difference between else if and separate if statements. With else if, conditions are mutually exclusive. Once one matches, the rest are skipped. With separate if statements, every condition is evaluated independently:

using System;

public class Program
{
    public static void Main()
    {
        int temperature = 35; // Try changing this to 25 or 15.

        Console.WriteLine("Using else if - only ONE message prints");

        if (temperature > 30)
        {
            Console.WriteLine("It's hot");
        }
        else if (temperature > 20)
        {
            Console.WriteLine("It's warm");
        }

        Console.WriteLine();

        Console.WriteLine("Using separate if statements - BOTH messages could print");

        if (temperature > 30)
        {
            Console.WriteLine("It's hot");
        }

        if (temperature > 20)
        {
            Console.WriteLine("It's warm");
        }
    }
}

If temperature is 35, the else if version prints only “It’s hot.” The separate if version prints both messages because both conditions are true and both are evaluated.

Nested if statements

You can place if statements inside other if statements to create more complex logic. This is called nesting:

using System;

public class Program
{
    public static void Main()
    {
        bool isLoggedIn = true;    // Try changing this to false.
        string userRole = "admin"; // Try changing this to "user".

        if (isLoggedIn)
        {
            if (userRole == "admin")
            {
                Console.WriteLine("Welcome, administrator!");
            }
            else
            {
                Console.WriteLine("Welcome, user!");
            }
        }
        else
        {
            Console.WriteLine("Please log in.");
        }
    }
}

The inner if statement only runs when the outer condition is true. This lets you build decision trees where later choices depend on earlier ones.

Best practices for nested conditionals

While nesting is powerful, it can quickly become hard to read. Follow these guidelines:

  • Limit nesting to two-three levels maximum. Deeper nesting makes code difficult to follow.
  • Consider extracting complex nested logic into separate methods with descriptive names.
  • Add comments explaining the business logic when nesting is necessary.
  • Look for opportunities to simplify with early returns or guard clauses.

If you find yourself with many nested if statements, it’s often a sign that you should refactor. Breaking the logic into smaller functions improves readability and makes testing easier.

Combining conditions with logical operators

Instead of nesting, you can often combine multiple conditions in a single if statement using logical operators. The && (AND) operator requires both conditions to be true. The || (OR) operator requires at least one condition to be true.

| Condition 1 | Condition 2 | && (AND) Result | || (OR) Result | | — | — | — | — | | true | true | true | true | | true | false | false | true | | false | true | false | true | | false | false | false | false |

using System;

public class Program
{
    public static void Main()
    {
        bool isLoggedIn = true;       // Try changing this to false.
        string userRole = "admin";    // Try changing this to "moderator" or "user".

        // Using AND - both conditions must be true
        if (isLoggedIn && userRole == "admin")
        {
            Console.WriteLine("Admin access granted");
        }

        // Using OR - at least one condition must be true
        if (userRole == "admin" || userRole == "moderator")
        {
            Console.WriteLine("You have elevated privileges");
        }
    }
}

Be careful with the OR operator when you have multiple conditions. Any single true condition triggers the if block, which can lead to unexpected behavior if you’re not thinking through all the combinations. Use parentheses to make complex conditions clearer:

if ((isLoggedIn && isPremium) || isAdmin)
{
 Console.Write(\"Access granted\");
}

When to use switch instead of if else

When you’re comparing a single variable against many specific values, a switch statement is often cleaner than a long if-else chain:

CriteriaIf-ElseSwitch
Number of conditionsBest for two-four conditionsBest for five+ discrete values
Type of comparisonRanges, complex expressionsSingle variable, exact matches
ReadabilityDecreases with more conditionsStays consistent
using System;

public class Program
{
    public static void Main()
    {
        int dayNumber = 2; // Try changing this to 1, 3, or 7.

        Console.WriteLine("Using if-else:");

        if (dayNumber == 1)
        {
            Console.WriteLine("Monday");
        }
        else if (dayNumber == 2)
        {
            Console.WriteLine("Tuesday");
        }
        else if (dayNumber == 3)
        {
            Console.WriteLine("Wednesday");
        }
        else
        {
            Console.WriteLine("Another day");
        }

        Console.WriteLine();

        Console.WriteLine("Using switch:");

        switch (dayNumber)
        {
            case 1:
                Console.WriteLine("Monday");
                break;

            case 2:
                Console.WriteLine("Tuesday");
                break;

            case 3:
                Console.WriteLine("Wednesday");
                break;

            default:
                Console.WriteLine("Another day");
                break;
        }
    }
}

Use if-else when you need to evaluate ranges (like score >= 90), complex boolean expressions, or when you have only a few conditions. Use switch when comparing one variable against many discrete values. 

Keep practicing C# If Else statement 

The if-else statement is one of those tools you’ll reach for every single day as a C# developer. It might seem simple at first, but mastering it — understanding evaluation order, knowing when to chain conditions with else if, and recognizing when to replace a long chain with a switch statement — will make your code cleaner and easier to maintain. 

Start with the basics covered here, experiment with the examples, and you’ll find yourself writing conditional logic with confidence in no time.