Logical Operators and Conditionals
As you program, you’ll often want to test whether a condition is true; for example, using the if statement, which you’ll see in the next chapter. C# provides a set of logical operators for this: and, or, and not. These operators work with the Boolean variables introduced in Chapter 3. Remember that a bool variable can hold only one of two values: true or false. Boolean expressions can be a bit confusing if you’re not used to them, but they’re critical to controlling the flow of your program, as you’ll learn in Chapter 5. Let’s take this slowly, with some examples. Start with three bool variables:
bool p = true; bool q = false; book r = true;
The variable p, by itself, evaluates to true, as does r, and q by itself evaluates to false. Easy enough. The and operator, which uses the symbol &&, evaluates to true only if both variables are true:
p && q // evaluates false p && r // evaluates true
The or operator, which uses the symbol ||, evaluates to true if either variable is true:
p || q // evaluates true
The only way for an or expression to evaluate to false is if both variables are false. Of course, if both variables are true, the expression still evaluates to true.
The not operator is slightly different; it operates on only a single variable, and evaluates to the opposite of the value of the variable:
!p // evaluates false !q // evaluates true
Tip
You may have noticed that the and and or operators use doubled symbols (&& and ||) instead of single ones (&
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access