Compress to/Expand Null Coalescing Operation
- 2 minutes to read
Purpose
Converts a ternary expression to an equivalent null coalescing operation and vice versa. Use of the null coalescing operations is the most compact way to specify null expressions in C#.
Availability
- The Compress to Null Coalescing Operation Refactoring is available when the caret is inside a “? :“ operator (short form of if). The operator should compare a variable to null. The same variable should be one of two alternative results.
- The Expand Null Coalescing Operation is available when the caret is on a statement that uses the ?? operator.
Usage
Place the caret on a compressible ternary expression.
Note
The blinking cursor shows the caret’s position at which the Refactoring is available.
private string CheckText(string text){ return (│text != null ? text : "null"); }
- Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
- Select Compress to Null Coalescing Operation from the menu (Expand Null Coalescing Operation if you are expanding the null coalescing operation).
After execution, the Refactoring compresses a ternary expression to an equivalent null coalescing operation or expands the null coalescing operation into an equivalent ternary expression.
private string CheckText(string text){
return (text ?? "null");
}
See Also