Back to Devexpress

Boolean to Enum

coderushforroslyn-115367-refactoring-assistance-boolean-to-enum.md

latest2.1 KB
Original Source

Boolean to Enum

  • Aug 03, 2020
  • 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.

  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.

csharp
class TestClass {
    private int TestMethod(TestMethodParam a) {
        if (a == TestMethodParam.Success)
            return 1000;
        else
            return 1024;
    }
}
public enum TestMethodParam {
    Success,
    Failure
}
vb
Public Class TestClass
    Private Function TestMethod(ByVal a As TestMethodParam)
        If (a = TestMethodParam.Success) Then 
            Return 1000
        Else 
            Return 1024
        End If 
    End Function 
End Class 
Public Enum TestMethodParam
    Success
    Failure
End Enum

See Also

Use Environment.NewLine

Use NameOf