# Boolean Logic

## 1. Learning Objectives

• What is a Boolean expression?
• Identify different operators used for creating Boolean expressions in C#
• How to formulate longer Boolean expressions

## 2. Boolean Expressions

Boolean expression is an expression that evaluates to either `true` or `false`. Boolean expressions are used in control statements to make decisions during the execution of a program.

Here are some examples of Boolean expressions:

`.css-k6dpb0{text-align:left;margin:0 0 16px 0;box-shadow:1px 1px 20px rgba(20,20,20,0.27);padding:2rem 1rem 1rem 1rem;overflow:auto;word-wrap:normal;border-radius:3px;webkit-overflow-scrolling:touch;}.css-k6dpb0 .token-line{line-height:1.3rem;height:1.3rem;font-size:15px;}.css-19w0oxy{position:absolute;right:0.75rem;top:0.25rem;border:0;background:none;border:none;cursor:pointer;color:rgb(248,248,242);border-radius:4px;margin:0.25em;-webkit-transition:all 250ms cubic-bezier(0.4,0,0.2,1) 0s;transition:all 250ms cubic-bezier(0.4,0,0.2,1) 0s;}.css-19w0oxy:hover{box-shadow:rgba(46,41,51,0.08) 0px 1px 2px,rgba(71,63,79,0.08) 0px 2px 4px;opacity:0.8;}`age > 21weather == "sunny"temperature <= 32A || Btrue``

Recall boolean data type `bool` can only take on two values: `true` or `false`. For this reason `bool` type variable can be used as a Boolean expression by itself.

## 3. Relational Operators

Relational operators evaluate the relationship between its operands. The operands can be variables or literal values of the same type (or such that they can be implicitly converted to same type) and the result of the operation is logical value `true` or `false`.

Below is a table listing relational operators in C#

SymbolDescriptionExample
`==`Equal to`a == b`
`!=`Not equal to`a != b`
`>`Greater than`a > b`
`<`Less than`a < b`
`>=`Greater than or Equal to`a >= b`
`<=`Less than or Equal to`a <= b`

In C# you can use `==` and `!=` operators to compare operands of different types for equality and inequality (including strings). Relational operators `<`, `>`, `<=`, `>=` can be used with all integral and floating-point numeric types.

### Examples with Relational Operators

``.css-lg150y{display:inline-block;width:2rem;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;opacity:0.3;}1int a = 4, b = 7;23Console.WriteLine(a > b);    // False4Console.WriteLine(a < b);    // True5Console.WriteLine(a >= 4);   // True6Console.WriteLine(12 <= b);  // False``

Equality operator `==` compares if the two operands are the same. The operation returns `false` when the operands are different. Note that when using it to compare string equality, the letter case of string value must match for the operation to evaluate as `true`.

``1Console.WriteLine("abc" == "abc");     // True2Console.WriteLine("hello" == "Hello"); // False3Console.WriteLine('C' == 'E');         // False``

If you want to create a Boolean expression to test if two operands are different, you can use not equals `!=` operator:

``1Console.WriteLine("ABC" != "abc");     // True2Console.WriteLine("bye" != "bye ");    // True3Console.WriteLine(23 != 23);           // False``

## 4. Logical Operators

Logical operators AND `&&` and OR `||` enable combining multiple Boolean expressions to create more complex logical expressions. Logical negation operator `!` (NOT) reverses the value of a Boolean expression. The operands must evaluate to Boolean values.

SymbolDescriptionExample
`&&`and`a && b`
`ǀǀ`or`a ǀǀ b`
`!`not`!a`

### Truth Tables for Logical Operators

To understand the expected results of AND, OR, and NOT operators review their truth tables:

ABAND
000
010
100
111
ABOR
000
011
101
111
ANOT
01
10
• AND operations will be true if and only if both operands are true and false otherwise
• OR will be true if at least one of the operands is true and false otherwise
• NOT will negate the truth value

### Examples with Logical Operators

Try changing values of `weather` and `weekend` and see how it changes the output.

### Combining Expressions to Create Complex Logical Expressions

AND and OR operators allow chaining multiple expressions together. You can combine an unlimited number of Boolean expressions using these operators. Refer to the section below for order of precedence or use parentheses to enforce a specific order of evaluation. In C# `&&` and `||` are short-circuiting operators, meaning once the truth value of the expression is known, the evaluation of the expression will end.

``1int a = 4,2    b = 3,3    c = 7;4bool success = true;56// Combining two expression -> False7Console.WriteLine(b > c || a < b);89// Combining 3 expressions -> True10Console.WriteLine(c == b || a == b || a != c);1112// This expression will short circuit -> True13Console.WriteLine(success || (b == c && a >= c));``

## 5. Relational and Logical Operator Precedence

The operator precedence determines the order in which expressions are evaluated. This becomes important when writing longer boolean expressions with multiple operators. Relational and logical operators are evaluated in this order, from highest to lowest:

#Operator
1.NOT `!`
2.Relational `<`, `>`, `<=`, `>=`
3.Equality `==`, `!=`
4.AND `&&`
5.OR `ǀǀ`

Operators of same type are evaluated left to right. Using parentheses allows enforcing alternative order of evaluation. See this document for complete reference.

## 6. Common mistakes with Boolean Expressions

#### 1. Mixing assignment and equality operator

Recall single equals sign `=` is used for assigning a value to a variable. If you are new to programming, it is very easy to make the mistake of using `=` in place of `==` and vice versa. The compilation of the program will fail and you will see an error if you misuse these operators.

#### 2. Evaluating incomparable data types

When performing relational comparison, the operands must be comparable. For example, this expression does not make sense: `5 > "Hi"`. Similarly, comparison `5.6D > 8.9M` is not allowed; but you can compare `5.6D > 8.9f` because `float` can be implicitly converted to `double`. You can avoid this issue by comparing operands of same type.

#### 3. Writing invalid expressions

The following is a very common mistake: `color == "orange" || "red"`. When combining Boolean expression using OR or AND operators, each operand must evaluate to `true` or `false`. `"red"` is a string; it is neither `true` or `false` and therefore cannot be evaluated. The proper way of writing this expression is: `color == "orange" || color == "red"`.

## 7. Summary

### What is a Boolean expression?

Boolean expression is a an expression that evaluates to `true` or `false`.

### Identify different operators used for creating Boolean expressions in C#

There are:

• Equality Operators: `==` and `!=`
• Relational Operators: `<`, `>`, `<=`, `>=`
• Logical Operators: `&&`, `||`, `!`

### How to formulate longer Boolean expressions

Relational expressions can be used to create simple expressions, for example:

``age > 21``

Logical AND and OR operators enable combining multiple expressions to create more complex logic:

``age > 21 && weather =="sunny" && isWeekend``