1.4.15 Boolean Expressions

A Boolean Expression Produces true or false

You already know the Boolean type:

bool

and its two values:

true
false

A Boolean expression is an expression that C# evaluates as a Boolean value.

That means its result is:

true

or:

false
A Boolean Field Can Be Used as a Boolean Expression

Suppose the Player class contains:

public bool isAvailable;

Then this expression:

player1.isAvailable

already produces a Boolean value.

If the field currently contains true, the expression evaluates to true.

If it currently contains false, the expression evaluates to false.

A Boolean Parameter Can Also Be an Expression

Consider:

public void SetAvailability(bool available)
{
    this.isAvailable = available;
}

Inside the method:

available

is a Boolean parameter.

Because its type is bool, using:

available

as an expression produces the Boolean value supplied by the caller.

For example:

player1.SetAvailability(true);

means that during the call:

available = true
Boolean Expressions Support Decisions

A simple decision can use an existing Boolean expression:

if (player1.isAvailable)
{
    System.Console.WriteLine("Player is available.");
}

The condition:

player1.isAvailable

must evaluate to true or false.

The if statement uses that result to choose whether its block runs.

The Expression and the Decision Are Different Ideas

In:

if (player1.isAvailable)
{
    System.Console.WriteLine("Player is available.");
}

the Boolean expression is:

player1.isAvailable

The if statement is the decision structure that uses the expression.

Boolean Literals Are the Simplest Boolean Expressions

These are Boolean values:

true
false

They can appear where a Boolean value is required.

For example:

player1.isAvailable = true;
Use Positive Names When Possible

A name such as:

isAvailable

is easier to interpret than a vague name such as:

flag

Read:

player1.isAvailable

as:

Then true means that statement is true and false means it is false.

Predict the Boolean Value Before Following the Path

Suppose the debugger shows:

player1.isAvailable = false

At:

if (player1.isAvailable)

you can predict that the condition evaluates to false.

The if block will therefore be skipped.

This connects:

Object diagram showing object state, then Boolean expression, then decision path.
ObjectState.
More Boolean Operators Come Later

Later Learning Activities teach equality comparisons, relational operators, string comparisons, null checks, and the ! operator.

For now, build the core idea: