Code inspection: 'if' statement can be rewritten as '??=' assignment
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 an assignment of a variable preceded by checking this variable for null with the if
expression, it suggests simplifying the assignment using the ??=
operator.
class TypeCheck
{
Type CheckType(object obj)
{
if (obj == null)
obj = new { };
return obj.GetType();
}
}
class TypeCheck
{
Type CheckType(object obj)
{
obj ??= new { };
return obj.GetType();
}
}
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