Skip to main content

Boolean to Enum

  • 2 minutes to read

Purpose

Use the Boolean to Enum Refactoring to convert two-state structures (method return types or method parameter types) into multiple-state structures. Enums have the following advantages.

  • Structure states describe themselves, which improves code readability.
  • You can easily add more states (e.g., Undefined), which makes your code more expandable.
  • The use of a unique string for each state makes the Refactoring easier.

Availability

Available when the caret is on a Boolean (bool) member, variable or method parameter.

Usage

  1. Place the caret on a boolean member, variable or method parameter as shown in the code below.

    Note

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

    class TestClass {
        private int TestMethod(bool a) {
            if (a)
                return 1000;
            else
                return 1024;
        }
    }
    
  2. Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
  3. Select Boolean to Enum from the menu.

The Boolean to Enum Refactoring makes the following changes.

  • Declares a new enumeration with two values — Success and Failure. These values substitute for true and false respectively.
  • Replaces the target Boolean variable with the newly-added enumeration everywhere in the code.
  • If the target variable is used in expressions, it is replaced by its comparison to the Success enumeration value.

The result of the Refactoring execution is shown in the code below.

class TestClass {
    private int TestMethod(TestMethodParam a) {
        if (a == TestMethodParam.Success)
            return 1000;
        else
            return 1024;
    }
}
public enum TestMethodParam {
    Success,
    Failure
}
See Also