Compress to/Expand Ternary Expression
- 2 minutes to read
Purpose
Converts an if-else conditional into an expression that uses a ternary operator (“? :“ operator in C#, inline IIf function in Visual Basic) and vice versa. These refactorings also support ref ternary expressions. Ternary expressions reduce the amount of code.
Availability
- The Compress to Ternary Expression refactoring is available when the caret is on a if statement that has a corresponding else block. The if and else blocks should contain one statement. These statements should be similar assignments, returns or method calls with different arguments.
- The Expand Ternary Expression is available when the caret is on an expression containing a ternary operator.
Usage
Place the caret on a compressible if-else expression.
Note
The blinking cursor shows the caret’s position at which the Refactoring is available.
- Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
Select Compress to Ternary Expression from the menu (Expand Ternary Expression if you are expanding the ternary expression).
After execution, the Refactoring compresses an if-else conditional into an equivalent ternary expression or expands the ternary expression into an equivalent if-else conditional.
public ref int GetValue(int[] arr1, int[] arr2) {
return ref (arr1 != null ? ref arr1[0] : ref arr2[0]);
}
See Also