Do more in less time. Block distracting websites with Cold Turkey Pro (Windows, Mac) »

Combine true/false expressions for complex C# if statements

A standard if statement typically evaluates a single true/false expression. That way our program makes basic decisions while it runs. But complex situations often require we evaluate several expressions, and then see whether an if statement’s code should run. Let’s explore how that works.

Complex if statements with multiple Boolean expressions

With a typical if statement or if/else statement, the if keyword condition usually consists out of a single Boolean expression. That single piece of code evaluates to true or false, and with that determines whether the if statement’s code should run or not.

But with a single true/false expression we can only evaluate basic situations. For instance, an if statement with the appDownloads > 1000 Boolean expression simply checks if there are more than a thousand downloads. But that’s all it looks for: it doesn’t evaluate other data. That also means we aren’t very precise with when that code runs: all it takes is 1,000 downloads.

At times such a simple if statement condition is all we need. But with complex programs we sooner or later need to check multiple values before we execute some if statement code. Say we want to check the number of downloads and the number of new members. That’s not something we can check with a single true/false expression.

Luckily, we can combine Boolean expressions in C#. When we do, we end up with a single true or false. Our if statement can then use that single value to determine whether it should execute its code block or not. To combine Boolean expressions, C# provides a set of logical operators for and, or, and not conditions (Liberty & MacDonald, 2009). These operators, which are also called Boolean operators, return a single true or false value (Sharp, 2013; Stephens, 2014).

Coding with C#’s logical true/false operators

Logical operators are critical to evaluate complex conditions and control the flow of our program. To see how we use them to program and, or, and not situations, let’s take a look at the first: and.

To see if two situations happened at the same time, we use the logical AND operator (&&). This type of Boolean operator only evaluates to true when both the expression on its left and the expression on its right are true too (Liberty & MacDonald, 2009; Sharp, 2013). For instance, for A && B to return true, both A and B need to be true separately from each other.

To check if either one or both situations happened, we use the logical OR operator (||). This operator returns true when the expression on its left is true, when the expression on its right is true, or when both the left and right expression are true (Liberty & MacDonald, 2009; Sharp, 2013). The result combined with || will only be false when both expressions are false too. For example, there are three situations in which A || B returns true: when A is true, B is true, or A and B are both true. Only when both A and B are false will A || B be false too.

The logical NOT operator (!) is a bit different. This one operates on a single Boolean value and evaluates to that value’s opposite (Liberty & MacDonald, 2009; Sharp, 2013). So when we put this logical operator before something that’s false, it returns true. And when placed before an expression that is true, it returns false.

We can think of this ! operator as the logical equivalent of the minus sign (Sempf, Sphar, & Davis, 2010). For instance, !A (read, “not A”) is true when A is false and false when A is true. In a similar way, for !B to return false, B itself has to be true.

The table below gives a summary of C#’s logical operators (Liberty & MacDonald, 2009; Stephens, 2014):

PurposeOperatorExampleResult
And&A & BOnly returns true when both A and B are true too. Returns false when A, B, or both are false.
Or|A | BReturns true when A, B, or both are true. Returns false when A and B are false too.
Negation!!AReturns true when A is false and false when A is true.
Xor (exclusive or)^A ^ BReturns true if A or B is true but both are not true.
And with short-circuit evaluation&&A && BOnly returns true when both A and B are true too. Returns false when A, B, or both are false.
Or with short-circuit evaluation||A || BReturns true when A, B, or both are true. Returns false when A and B are false too.

Let’s see how we can use these logical operators when programming if statements.

Example: multiple expressions in an if/else statement

The console application below checks if the goals for an app’s new users and number of downloads are reached. To programmatically check those goals, we use the && logical operator to combine two separate true/false expressions in an if/else statement’s condition. The code looks like:

using System;

namespace CodeStudies
{
    class CodeStudies_Example
    {
        static void Main(string[] args)
        {
            int newMembers   = 75;
            int appDownloads = 1042;

            if ((newMembers > 50) && (appDownloads > 1500))
            {
                Console.WriteLine("We've reached our initial target!");
            }
            else
            {
                Console.WriteLine("We didn't reach the target.");
                Console.WriteLine("Possible causes:"); 
                Console.WriteLine("not enough signups, too few downloads, or both.");
            }
        }
    }
}

This example generates the following output:

We didn't reach the target.
Possible causes: 
not enough signups, too few downloads, or both.

Let’s analyse the programming example and see how it came up with this output. First, we declared and initialised two variables like so:

int newMembers   = 75;
int appDownloads = 1042;

Next in the code is the following if/else statement:

if ((newMembers > 50) && (appDownloads > 1500))
{
    Console.WriteLine("We've reached our initial target!");
}
else
{
    Console.WriteLine("We didn't reach the target.");
    Console.WriteLine("Possible causes:"); 
    Console.WriteLine("not enough signups, too few downloads, or both.");
}

In the condition of the if keyword here we evaluate multiple expressions. The first checks whether more than 50 people signed up. For that, we evaluate whether the newMembers variable is greater than (>) 50. The second evaluates if the number of downloads (appDownloads) is bigger than (>) 1500.

To make the indented code below the if statement only execute when both Boolean expressions are true, we combine them with the logical AND operator (&&). That operator only returns true when its left and right expressions are both true. That means before the if code block to run, we need more than 50 new members and 1,500 or more app downloads.

While the newMembers variable holds a value of 75 (and so that part of the condition evaluates to true), the appDownloads variable has a value of 1,042. That makes the second part of the if statement’s condition false, which in turn makes the entire condition false. After all, the result combined with && is false as soon as one (or both) of the expressions are false too.

For our if/else statement that means the if code block doesn’t run. Instead the code that’s indented below else runs. That code block executes the Console.WriteLine() method twice to print that the target wasn’t reached, including possible causes.

We know those possible reasons based on how we wrote the if/else statement: the else code runs when the condition with the logical AND operator (&&) evaluates to false. That happens when one or both expressions we combined with && are false. For us, that means either the number of downloads or the new members weren’t sufficient.

At this point in the program, we cannot say which reason (not enough new members, not enough downloads, or both) made the else code block execute. All we know for sure is that the if statement condition evaluated to false. Only when there’s one Boolean expression in the condition of an if/else statement (like newMembers > 200) can we know for sure why the else code executes (when newMembers is 200 or less).

Example: multiple logical operators in a single if statement

Besides a single logical operator in an if statement’s condition, we can also use several of those operators. That way we code much more complex situations. Let’s see an example of that.

The if statement below executes the Console.WriteLine() method in one of two situations. The first is when there are more than 225 new members and 10,000+ app downloads. The second situation happens when 100 or new members signed up and when the downloads are more than 25,000.

We use four Boolean expressions to translate those situations into code, one for each requirement. Then we combine those expressions with the logical AND (&&) and OR (||) operators:

if (((newMembers > 225) && (appDownloads > 10000)) || 
    ((newMembers <= 100) && (appDownloads > 25000)))
{
    Console.WriteLine("Successfully launched the latest application!");
}

With a clever use of parentheses (( and )), the first part of this if statement’s condition contains two Boolean expressions that are combined with the logical AND (&&) operator. The second part also has two expressions stringed together with &&. And we combine those two parts with the logical OR operator (||). This way only the first or second part has to be true before the if statement’s code runs.

The first part of the condition checks if the newMembers variable is greater than (>) 225. We use && to combine that expression with the second one that checks whether the appDownloads variable is bigger than 10,000. In the other part of the if statement’s condition we check if newMembers is less than or equal to (<=) 100 and (&&) the downloads (appDownloads) were higher than 25,000.

So before this if statement’s code run, we either want more than 225 new members and more than 10,000 downloads, or at most 100 new members but with more than 25,000 downloads.

Parentheses affect the order in which code executes. With multiple parentheses, C# executes the code in the innermost parentheses first (Sempf et al., 2010). For the if statement above, first the individual expressions (like newMembers > 225) evaluate. Then the two expressions combined with the AND operator (like (newMembers > 225) && (appDownloads > 10000)) execute. And then the true/false outcome of the first and second part is combined with the || operator to see if the code inside the if statement should run or not.

Summary

When we evaluate several true/false expressions in the condition of an if statement, our program can deal with increasingly complex situations. But no matter how complex an if statement’s condition is, it always needs to evaluate to true or false. That means the Boolean expressions have to result in a single value.

We do that with logical operators. One common logical operator is the AND operator (&&), which only returns true when the expression on its left and the expression on its right are true too. When its left expression, right expression, or both are false, then the result combined with && is also false. Another often-used logical operator is the OR operator (||). This one returns true when the expression on its left, the expression on its right, or both are true. Only when both the left and right expressions are false, will || return false too.

We can also use several logical operators in the condition of a single if statement. When we do, we’ll have to use parentheses to specify the order in which C# should evaluate them.

References

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.

Sempf, B., Sphar, C., & Davis, S.R. (2010). C# 2010 All-In-One for Dummies. Hoboken, NJ: John Wiley & Sons.

Stephens, R. (2014). C# 5.0 Programmer Reference. Indianapolis, IN: John Wiley & Sons.