ReSharper 2018.2 Help

Code Inspection: '?:' expression can be re-written as '??' expression

If you want to assign a value, pass an argument, or return from a method based on the nullability of an identifier, the clearest syntax you can use in these cases is the ?? (null-coalescing) operator.

Therefore, whenever ReSharper encounters a conditional ?: (ternary) operator in the above-mentioned contexts, it suggests simplifying the expressions using the ?? operator.

Here is an example of a quick-fix suggested by this inspection:

Suboptimal code

After the quick-fix

void Foo(string input) { Console.WriteLine($"The input is {(input != null ? input : "empty")}"); }

void Foo(string input) { Console.WriteLine($"The input is {(input ?? "empty")}"); }

Speaking about performance of both operators, there is no observable difference. Actually, the ?? is even a tiny bit faster.

Last modified: 5 November 2018

See Also