BlackWaspTM
C# Programming
.NET 1.1+

C# Boolean Operators (2)

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.

AND Operator

The AND operator is used to compare two Boolean values. It returns true 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 (&):

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 (|):

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:

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
28 August 2006