1.6.8 Using the Not (!) Operator

Overview

The ! operator reverses a Boolean value: !true is false, and !false is true. In Zoo, GetIsPregnant() returns true when an Animal already has a Baby. Negating that result asks whether the Animal is not pregnant.

if (!this.GetIsPregnant())
{
    // Continue only when Baby is null.
}

With a null Baby, GetIsPregnant() returns false, so !this.GetIsPregnant() is true. With an existing Baby, the method returns true, so the negated condition is false. Place ! before the Boolean expression you want to reverse.

Trace the Negated Result
Compare if (this.GetIsPregnant()) with if (!this.GetIsPregnant()): the branch selected for each Animal flips. Parentheses in !(a && b) reverse the combined result, while !a && b reverses only a. Those are different expressions.
Trace the Negated Result
  • New
  • Changed
  • Removed

Compare if (this.GetIsPregnant()) with if (!this.GetIsPregnant()): the branch selected for each Animal flips. Parentheses in !(a && b) reverse the combined result, while !a && b reverses only a. Those are different expressions.

Trace the Outcome

Test once with Baby == null and once with a Baby object. Predict the original method’s return value, apply !, and then identify the branch taken. Do not use ! on a non-Boolean value.

The negation applies to the Boolean result of the method call, not to the Animal object. In !this.GetIsPregnant(), the method runs first and returns true or false; ! flips that result. If the method returns true, the code inside the if is skipped. Read the full condition aloud before tracing the branch.