Back to Devexpress

Reverse Boolean

coderushforroslyn-115574-refactoring-assistance-reverse-boolean.md

latest1.7 KB
Original Source

Reverse Boolean

  • Aug 03, 2020
  • 2 minutes to read

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.

  2. Press 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.

csharp
bool notFound = Search(data, ref i);
if (notFound)
    Console.WriteLine($"Found record at the position {i}");
else {
    Console.WriteLine("No records found.");
    return;
}
vb
Dim notFound As Boolean = Search(data, i)
If notFound Then
    Console.WriteLine($"Found record at the position {i}")
Else
    Console.WriteLine("No records found.")
    Return
End If

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

See Also

Reverse Conditional

Simplify Expression