The secret to productivity? Block internet distractions. Learn more about Cold Turkey Pro »

Simplify and remove nested if statements with C#’s logical operators

When we program complex situations in C#, sooner or later or code becomes hard to understand and fix with all those different if statements. Luckily, we can simplify if statements in multiple ways. That makes it possible to get the same program behaviour, but with less code that also clearer. Let’s see how.

Simplify nested if statements with C#’s logical operators

Thanks to if statements our program doesn’t run in a straight line from start to finish, but makes decisions based on values and inputs. We make a basic if statement with the if keyword followed with a Boolean expression between parentheses. After that comes code that should run when the true/false condition evaluates to true.

We can surround that code with braces ({ and }) that create a code block. Then inside such a code block we can place regular C# statements. Or we nest another if statement there (Dorman, 2010; Liberty & MacDonald, 2009). In that latter case the second if statement executes based on the first, which makes it possible to evaluate complex situations.

But sometimes nested if statements make code too complex. Each additional if keyword also creates more indentation, which adds up to make code hard to read and understand. With enough nested if statements we even lose track of where we are in the code, and what lines come before and after the if keywords. Thankfully, it’s easy to simplify nested if statements with C#’s logical operators.

Those operators combine several true/false expressions into a single true or false (Liberty & MacDonald, 2009). When we think about it, that’s like how nested if statements work. After all, with multiple if statements inside each other, the innermost only executes based on the combination of all previous true/false conditions.

The two logical operators we use to simplify nested if statements are (Liberty & MacDonald, 2009; Sharp, 2013):

See using logical operators with C#’s if statements for more on these operators and how we can use them with the different if statements.

With a strategic use of these operators we can simplify multiple nested if statements into a single if statement. Let’s see some examples of that, as well as situations in which the simplification doesn’t work.

Replace nested if statement with logical AND operator

The typical way to rewrite a nested if statement into an easier-to-read if statement is when there’s just one nested if. In that case we simply combine the conditions of both if keywords with the logical AND operator (&&).

Say we have the following nested if statement:

if (yearsExperience > 10)
{
    if (!newHire)
    {
        Console.WriteLine("Eligible for promotion.");
    }
}

This if statement checks whether yearsExperience has a value greater than 10. When it has, the nested if statement runs. That one uses the logical NOT operator (!) to see if newHire is false. When that’s also the case, the Console.WriteLine() method prints some information to our console window.

And so before that code of the nested if statement runs, both if conditions have to be true. That means we can also combine those true/false expressions into a single if condition. We do that with the logical AND operator (&&) like this:

if ((yearsExperience > 10) && !newHire)
{
    Console.WriteLine("Eligible for promotion.");
}

Here Console.WriteLine() still executes based on the same conditions as earlier. It’s just that now we removed the unneeded nested if statement by combining the two if statement conditions. This way we got less code and less indentation, making the code clearer and easier to read.

Nested if statements that cannot be simplified

Now we cannot simplify all nested if statements with the logical AND operator (&&) like we did above. The requirement to turn multiple if statements into a single one is: there should be no lines of code between the if keywords. As soon as there is, we cannot collapse the if statements together.

For instance, here we cannot eliminate the second nested if statement:

if (yearsExperience > 10)
{
    if (!newHire)
    {
        Console.WriteLine("Invite for an interview.");
        
        if (highAchiever)
        {
           Console.WriteLine("Hire this person.");
        }
    }
}

Here the first Console.WriteLine() statement prints some information based on two conditions: yearsExperience > 10 and !newHire. But these conditions are independent from the true/false expression of the third if keyword. That means we cannot rewrite the code so that this Console.WriteLine() line depends on the third if condition (highAchiever).

An attempt to combine those three if conditions together is in fact incorrect:

if ((yearsExperience > 10) && !newHire && highAchiever)
{
    Console.WriteLine("Invite for an interview.");
    Console.WriteLine("Hire this person.");
}

What makes this if statement wrong is that it changed the behaviour of the previous nested if statements. That happens because now the Console.WriteLine() line that invites a person for an interview depends on the highAchiever true/false expression. In the previous example that wasn’t the case.

When we collapse the if statements into one here, we change the meaning of the code. That means we cannot simplify the code here by combining the nested if statements.

When there’s a line of code between an if statement and its nested if statement, we cannot use logical operators (&& and ||) to code the nested if statement away. Trying to do so changes the meaning and behaviour of the code.

The best we can do with the above example is collapse the first and second if statement into one condition, and then still use a nested if statement for the highAchiever condition:

if ((yearsExperience > 10) && !newHire)
{
    Console.WriteLine("Invite for an interview.");
    
    if (highAchiever)
    {
       Console.WriteLine("Hire this person.");
    }
}

Here we at least improved a bit of code and got rid of some indentation. This simplified the original code, but with consideration for which conditions made each Console.WriteLine() statement execute.

Sometimes, however, it’s not possible to remove any nested if statement. That happens when there’s a statement after each if keyword, like here:

if (yearsExperience > 10)
{
    Console.WriteLine("Highly experienced candidate.");
    
    if (!newHire)
    {
        Console.WriteLine("Negotiate contract.");
        
        if (highAchiever)
        {
            Console.WriteLine("Hire this person.");
        }
    }
}

Since we have code here between the first and second if keyword, we cannot join these three if statements together into one. And so with code like this we’re stuck with multiple if statements and several levels of indentation. Now let’s continue our discussion about the if statements we can simplify and improve.

Replace multiple nested if statements with C#’s && operator

Another situation that gives room for improvement is when we end up with several nested if statements, like this:

if (yearsExperience > 10)
{
    if (!newHire)
    {
        if (highAchiever)
        {
            if (jobPerformance > 7.5)
            {
                Console.WriteLine("Eligible for promotion.");
            }
        }
    }
}

Here we check four conditions, each with its own if keyword. There’s one Console.WriteLine() statement inside the last nested if statement, but no code between the different if keywords. That means we can combine the different conditions together.

To join the different conditions into a single if statement we use the logical AND operator (&&). That means each individual true/false expression has to be true before the if statement’s entire condition is true. And that’s just like how it works with the nested if statements above: all those also need to evaluate to true before the Console.WriteLine() line runs.

That means the simplified code becomes:

if ((yearsExperience > 10) && !newHire && 
    highAchiever && (jobPerformance > 7.5))
{
    Console.WriteLine("Eligible for promotion.");
}

With this single if statement we still print the message with Console.WriteLine() in the same situations. It’s just that we got code that’s much shorter.

There’s no real limit on how many nested if statements the && operator can combine in a single if statement. But a lot of true/false expressions in one if condition make code hard to read and understand. At that point a single if statement is less clear than one or two nested if statements. See simplify complex code with nested if statements for how nested if statements can make code easier to read.

Simplify nested if statements inside C#’s if/else statement

So with the logical AND operator (&&) we can simplify if statements placed inside another. But we can also simplify nested if statements that happen inside if/else statements. For that we use the logical OR operator (||). This operator returns true when its left, right, or both values are true. Only when both values combined with the logical || operator are false will || return false too.

There aren’t many situations in which the logical OR operator (||) can simplify if/else statements. That’s because of a specific requirement for doing so: the nested if statement that appears in the if and else part of the if/else statement has to be identical.

Let’s say we got the following if/else statement in our program:

if ((yearsExperience > 3) && highAchiever)
{
    if (jobPerformance > 7.5)
    {
        Console.WriteLine("Time for promotion.");
    }
}
else if ((yearsExperience > 10) && !newHire)
{
    if (jobPerformance > 7.5)
    {
        Console.WriteLine("Time for promotion.");
    }
}

These two nested if statements both evaluate if the person’s performance is higher than 7.5 (jobPerformance > 7.5). In that case they execute the Console.WriteLine() method and say it’s time for promotion. But before any of these nested if statements can run, the if or else if portion of the if/else statement has to be true.

Since both nested if statements are identical here, we can simplify this code with C#’s logical operators. Rewriting the code into a single if statement looks like:

if ((((yearsExperience > 10) && !newHire) ||
    ((yearsExperience > 3) && highAchiever)) &&
    (jobPerformance > 7.5))
{
    Console.WriteLine("Time for promotion.");
}

Here the logical && operator combines the two conditions we saw earlier in the if and else branch of the if statement. Since only one of those two are needed to execute the code, we combine them with the logical || operator.

Both those conditions however need to be combine with the condition of the previous nested if statement (jobPerformance > 7.5). And so we join that condition here with the logical && operator. Then inside this if statement we have the same Console.WriteLine() method call as in the previous example.

As this example also shows, a shorter, single if statement isn’t necessarily more readable and easier to understand. Luckily, interim variables make complex if statements easier to read . For instance:

bool experiencedEmpl = (yearsExperience > 10) && !newHire;
bool promisingEmpl   = (yearsExperience > 3) && highAchiever;
bool highJobPerf     = (jobPerformance > 7.5);

if ((experiencedEmpl || promisingEmpl) && highJobPerf)
{
    Console.WriteLine("Time for promotion.");
}

This way we not only simplified our code with the logical && and || operators, but also made it easier to understand and debug.

Summary

If statements inside others create nested if statements. With those we can evaluate complex conditions and make our application adapt to various situations. However, they also make code harder to read, understand, and debug. But we simplify nested if statements when we join their conditions together with C#’s logical operators.

Those operators are && and ||. The logical AND operator (&&) returns true when the expression on its left and the one on its right are both true. When one or both are false, this logical operator returns false too. The logical OR operator (||) returns true when the value on its left, right, or both are true. Only when both the left and right value are false will || return false too.

To simplify a nested if statement we use the logical AND operator (&&) to combine its condition with that of the previous if statement. For this to work there should not be additional code between those two if keywords.

Another possible improvement is when an if/else statement has an identical nested if statement in its if and else code block. In that case we combine the two conditions of the if and else keywords together with ||. And then use && to add that Boolean outcome with a nested if statement condition.

Rewriting our program’s code with logical operators takes a bit of work, but has multiple benefits in the long run: the reduced levels of indentation make code shorter, easier to read, and quicker to fix. And when collapsing multiple if statements into one creates a lot of expressions, we can improve readability with interim variables.

Learn more

References

Dorman, S. (2010). Sams Teach Yourself Visual C# 2010 in 24 Hours. Indianapolis, IN: Sams/Pearson Education.

Liberty, J. & MacDonald, B. (2009). Learning C# 3.0: Master the Fundamentals of C# 3.0. Sebastopol, CA: O’Reilly Media.

Sharp, J. (2013). Microsoft Visual C# 2013 Step by Step. Microsoft Press.