Compress to Ternary Expression
In This Article
Converts an if/else conditional into an expression that uses a ternary operator (“? :” operator in C# and C++, IIf operator in Visual Basic).
#Purpose
This refactoring can help you avoid code duplication. It can compress two similar code lines within if and else blocks into a single-line expression, eliminating the need to make future changes in two places.
#Availability
Available from the context menus or via shortcuts:
- when the caret is on a if statement that has the corresponding else block. Both if and else blocks should contain one statement. These statements should be similar assignments or method calls with different arguments.
#Notes
- This refactoring is the functional opposite of Expand Ternary Expression.
#Example
│if (a)
b = 10;
else
b = 20;
│If a Then
b = 10
Else
b = 20
End If
Result:
b = a ? 10 : 20;
b = If(a, 10, 20)
#Animation
See Also