Reverse Boolean

Purpose

Reverses the logical meaning of a Boolean variable, and appropriately inverts all references and assignments to the variable to ensure program behavior remains unchanged. Use this Refactoring when you need to reverse the semantic meaning of a Boolean variable (e.g., changing "notFound" to "found"), and can clean up hard-to-read expressions (e.g., "!notFound" can become simply "found" in C#).

Availability

Available when the caret is on the name of a boolean variable in its declaration.

Usage

  1. Place the caret on a boolean variable declaration.

    Note

    The blinking cursor shows the caret's position at which the Refactoring is available.

    bool notFound = !Search(data, ref i);
    if (!notFound)
        Console.WriteLine($"Found record at the position {i}");
    else {
        Console.WriteLine("No records found.");
        return;
    }
    
  2. Use the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions Menu.
  3. Select Reverse Boolean from the menu.

After execution, the Refactoring changes the variable value to the opposite one and inverts it in every reference and assignment. The variable name should be changed manually.

bool notFound = Search(data, ref i);
if (notFound)
    Console.WriteLine($"Found record at the position {i}");
else {
    Console.WriteLine("No records found.");
    return;
}

In the example above, the name of the variable should be changed to found to match the semantic meaning.

See Also