Code inspection: '??' condition is known to be null or not null
Category: Redundancies in Code
ID: ConstantNullCoalescingCondition
EditorConfig: resharper_constant_null_coalescing_condition_highlighting=[error|warning|suggestion|hint|none]
Language: C#
Requires SWA: No
tip
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.
A null-coalescing expression works as follows. The left-hand operand is evaluated first, and if it is null, the right-hand operand is evaluated and the result becomes the result of the whole expression.
However, redundant null-coalescing expressions produce dead code and impede readability. As it follows from the logic of the ??
operator, using null
as the right-hand operand does not make sense. Below, ReSharper suggests removing the right-hand operand null
together with the ??
operator, because if the newCategory
is null, then null will be assigned to the Category
anyway:
Suboptimal code
public class Customer{ public string Category { get; set; } private void ChangeCategory(string newCategory) { Category = newCategory ?? null; } /* … */}
After the quick-fix
public class Customer{ public string Category { get; set; } private void ChangeCategory(string newCategory) { Category = newCategory; } /* … */}
Another situation when the null-coalescing operator is redundant is when the left-hand operand can never be null. In this case, the right-hand operand never gets reached and ReSharper suggests removing the unreachable code:
Suboptimal code
string name = "John";Console.WriteLine(name ?? "empty");
After the quick-fix
string name = "John";Console.WriteLine(name);