Codecademy Logo

Learn C#: Logic

Boolean Type

The bool data type can be either true or false and is based on the concept that the validity of all logical statements must be either true or false. A boolean expression is any expression that evaluates to, or returns, a boolean value.

Booleans encode the science of logic into computers, allowing for logical reasoning in programs. In a broad sense, the computer can encode the truthfulness or falseness of certain statements, and based on that information, completely alter the behavior of the program.

bool skyIsBlue = true;
bool penguinsCanFly = false;
Console.WriteLine($"True or false, is the sky blue? {skyIsBlue}.");
// This simple program illustrates how booleans are declared. However, the real power of booleans requires additional programming constructs such as conditionals.

Logical Operators

Logical operators receive boolean expressions as input and return a boolean value.

The && operator takes two boolean expressions and returns true only if they both evaluate to true.

The || operator takes two boolean expressions and returns true if either one evaluates to true.

The ! operator takes one boolean expression and returns the opposite value.

// These variables equal true.
bool a = true && true;
bool b = false || true;
bool c = !false;
// These variables equal false.
bool d = true && false;
bool e = false || false;
bool f = !true;

Truth Tables

A truth table is a way to visualize boolean logic. Since booleans only have two possible values, that means that we can compactly list out in a table all the possible input and output pairs for unary and binary boolean operators.

The image below gives the truth tables for the AND, OR, and NOT operators. For each row, the last column represents the output given that the other columns were fed as input to the corresponding operator.

Truth tables for AND, OR, and NOT. Each table cell contains either True or False.

Learn more on Codecademy