JetBrains Rider 2024.2 Help

Code inspection: 'if' statement can be rewritten 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 JetBrains Rider encounters an if 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:

private string _name; public string Name { get { if (_name == null) _name = "Anonymous"; return _name; } set { _name = value; } }
private string _name; public string Name { get { return _name ?? (_name = "Anonymous"); } set { _name = value; } }

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

Last modified: 23 September 2024