1.4.21 Using the Not (!) Operator

The ! Operator Reverses a Boolean Value

The C# not operator is:

!

It reverses a Boolean result.

If an expression is true, applying ! makes it false.

If an expression is false, applying ! makes it true.

Use ! with a Boolean Field

Suppose:

player1.isAvailable

is true.

Then:

!player1.isAvailable

is false.

Read:

!player1.isAvailable

as:

Use ! in an if Statement

For example:

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

The block runs when:

player1.isAvailable = false

because ! reverses that value to true for the condition.

Trace the Expression in Two Steps

Suppose:

player1.isAvailable = false

Evaluate:

!player1.isAvailable

in two steps:

Activity diagram showing player1.isAvailable false, then !false true.
Player1IsAvailableFalse.
  • New
  • Changed
  • Removed

The if block runs.

Use ! with a Grouped Boolean Expression

Consider:

!(score >= 3)

First evaluate:

score >= 3

Then reverse the result.

If:

score = 2

then:

Activity diagram showing score = 3 false, then !false true.
Score3False.
  • New
  • Changed
  • Removed

Parentheses make the evaluation target clear.

Do Not Read ! as an Assignment or State Change

This:

!player1.isAvailable

does not change the stored value of:

player1.isAvailable

It only reverses the Boolean result for the current expression.

If the field is false before the expression, it is still false afterward unless another statement assigns a new value.

Use Positive Boolean Names When Possible

A field such as:

isAvailable

works naturally with !:

!isAvailable

which reads:

Clear naming makes negation easier to reason about.

Predict Before Executing

Before stepping through:

if (!player1.isAvailable)

identify the current field value.

For:

isAvailable = true

evaluate:

!true = false

Predict:

The debugger can then confirm the path.

The Main Rule
Activity diagram showing !true false, then !false true.
TrueFalse.
  • New
  • Changed
  • Removed

The not operator reverses a Boolean result. It does not modify the stored value by itself.