BlackWasp
C# Programming
.NET 1.1

C# Boolean Operators

The eighth part of the C# Fundamentals tutorial moves away from arithmetic and takes a first look at the Boolean data type and its available operators. Boolean data is used extensively in programming and an understanding of its features is essential.

A Review of the Boolean Data Type

In the third part of the C# Fundamentals tutorial I introduced the Boolean data type. A Boolean variable is capable of storing just two values. These values are true and false, also known as truth values. The following examples show the simple assignment of Boolean variables, which are declared using the bool keyword.

bool grassIsGreen = true;
bool cowsGoBaa = false;

Boolean Logic Operators

The Boolean data type has its own set of logical operators. These operators allow the programmer to test or adjust the value of the Boolean variable in a similar manner to any other variable. The resultant values may be used in conditional programming statements to determine the direction of flow through the code. Conditional programming will be looked at when we examine program flow later in the tutorial. For this article, the next sections describe the various operators available to the C# developer.

Equivalence Operator

The equivalence, or equality, operator is a binary operator in that it operates on two values or operands. The equivalence operator makes a simple comparison between the two operands and returns a truth value indicating if they match exactly. The operator symbol for equivalence is a double-equals signs (==).

bool a = true;
bool b = false;
bool c = false;
bool result;

result = a == b;        // result = false
result = b == c;        // result = true
result = b == false;    // result = true

Inequality Operator

The inequality operator compares two operands and returns true if the two values do not match exactly. The operator provides the opposite functionality to the equivalence operator mentioned above. The operator symbol for non-equivalence is an exclamation mark and an equals signs (!=). It is read as not equal to for reasons that will become apparent shortly.

bool a = true;
bool b = false;
bool c = false;
bool result;

result = a != b;        // result = true
result = b != c;        // result = false
result = b != true;     // result = true

NOT Operator

The NOT operator is a unary operator in that it operates on a single operand. The NOT operator simply switches the value of a Boolean variable or value. If the original value is true then the returned value is false; if the original value is false, the return value is true. The NOT operator is often known as the binary complement.

bool a = true;
bool b = false;
bool result;

result = !a;            // result = false
result = !b;            // result = true
result = !true;         // result = false

AND Operator

The AND operator is used to compare two Boolean values. The AND operator returns true only if both of the operands are true. This can be represented by the following truth table which shows the two operands and the result of every possible AND operation.

Operand 1Operand 2Result (AND)
falsefalsefalse
falsetruefalse
truefalsefalse
truetruetrue

The AND operator is represented by the ampersand character (&). The following shows some examples of its use:

bool a = true;
bool b = false;
bool c = true;
bool result;

result = a & b;         // result = false
result = a & c;         // result = true
result = a & (a == c);  // result = true

OR Operator

The OR operator is similar to AND as it is used to compare two Boolean values. The OR operator returns true if either of the operands are true. This can be represented by the following truth table.

Operand 1Operand 2Result (OR)
falsefalsefalse
falsetruetrue
truefalsetrue
truetruetrue

The OR operator is represented by the bar character (|). The following shows some examples of its use:

bool a = true;
bool b = false;
bool c = false;
bool result;

result = a | b;         // result = true
result = b | c;         // result = false
result = a | b | c;     // result = true

Exclusive OR (XOR) Operator

The exclusive OR, or XOR, operator is a specialised version of OR. The XOR operator returns true if either or the operands is true but false if they are both true, ie. exactly one of the two operands must be true. This can be represented by the following truth table.

Operand 1Operand 2Result (XOR)
falsefalsefalse
falsetruetrue
truefalsetrue
truetruefalse

The caret character (^) represents the exclusive OR operator. The following shows some examples of its use:

bool a = true;
bool b = false;
bool c = true;
bool result;

result = a ^ b;         // result = true
result = a ^ c;         // result = false
result = a ^ true;      // result = false

Short-Circuit Logic Operators

The C# programming languages includes two further operators for use with Boolean values. These are the short-circuit versions of AND and OR. They are included in code using either a double-ampersand (&&) or double-bar (||).

When evaluating an AND where the first operand evaluates to false, the result of the operation will be false regardless of the value of the second operand. Similarly, when evaluating an OR operation where the first operand evaluates to true, we know the result will always be true. The short-circuit versions of AND and OR use this logic to create more efficient code by not evaluating the second operand on these occasions. Consider the following examples:

bool a = true;
bool b = false;
bool result;

result = a && b;        // result = false
result = b && a;        // result = false, a is not evaluated
result = a || b;        // result = true, b is not evaluated
result = b || a;        // result = true

In many situations, the short-circuit and standard versions of AND and OR work in exactly the same manner. It is important to recognise that when the operation is short-circuited the second operand is not evaluated and so any other function linked to the evaluation is not carried out. The following example illustrates this:

int divisor = 0;
int quantity = 100;
bool ok;

// Check if quantity divides without reminder (divisor must not be zero)
ok = (divisor != 0) & (quantity % divisor == 0);

On execution of this program an error will be generated. On the line of code where the variable "ok" is assigned, two operations are carried out. Firstly the divisor value is checked to ensure that it is not zero. Secondly, the quantity is divided by the divisor. As the second operand is evaluated as one hundred divided by zero, a divide by zero error is generated and the program stops.

In the above example, it would be better to check the divisor and only continue to perform the modulus operation if it is not zero. This can be achieved by using the short-circuit version of AND.

int divisor = 0;
int quantity = 100;
bool ok;

// Check if quantity divides without reminder (divisor must not be zero)
ok = (divisor != 0) && (quantity % divisor == 0);

The above example shows a positive use of the short-circuit operators to avoid errors or exceptions occurring. It is important to understand that there can be drawbacks to not evaluating the second operand. If, for example, an increment operator (++) is used in the second operand, not evaluating this would mean that a variable's value would not be adjusted. Inappropriate use such as this can lead to bugs that are difficult to identify and resolve.

Operator Precedence

We can now extend the operator precedence table further using the new operators discussed in this article.

Parentheses Operator
()
Increment / Decrement Operators
++(postfix) --(postfix) ++(prefix) --(prefix)
Complement Operators
!
Basic Arithmetic Operators
* / % + -
Equivalence Operators
== !=
Logic Operators
& ^ | && ||
Assignment Operator
=
Compound Assignment Operators
*= /= %= += -=
Link to this Page28 August 2006
RSS RSS Feed