Fix the MA0082 code fix for operands of another type or nullable operands

Merged
ME
2mo ago
+126-2

What

The MA0082 code fix calls IsNaN on the type that declares the NaN constant, not on the type of the comparison, and it ignores nullable operands. Both cases produce code that doesn't compile:

bool A(double d) => d == float.NaN;   // fixed to float.IsNaN(d)  -> CS1503
bool B(double? d) => d == double.NaN; // fixed to double.IsNaN(d) -> CS1503

Expected: double.IsNaN(d) and double.IsNaN(d.GetValueOrDefault()).

Fix

  • IsNaN is now called on the type used by the comparison, which is the converted type of the NaN operand without Nullable<T>. So doubleValue == float.NaN becomes double.IsNaN(doubleValue) and floatValue != double.NaN becomes !double.IsNaN(floatValue). Generic math (T.IsNaN(value)) is unchanged.
  • When the other operand is nullable, the argument becomes value.GetValueOrDefault(), with parentheses when needed. A lifted comparison with NaN is always false (!= is always true). double.IsNaN(value.GetValueOrDefault()) is true only when the value is not null and is NaN, which is what the fix is meant to express.
  • The fix is no longer offered when the result would not compile: the comparison type is not a floating-point type, or the other operand has no built-in implicit conversion to it (for example, a user-defined operator ==(Sample, double)). The replacement is now computed before RegisterCodeFix, so the fix is registered only when the replacement can be built.
  • The MA0082 docs now describe the fix for these cases.

Tests

  • Added Comparisons_CodeFix_NaNOfAnotherType, Comparisons_CodeFix_NullableOperand and Comparisons_UserDefinedOperator_NoCodeFix. The first two failed before the fix.
  • Ran DoNotNaNInComparisonsAnalyzerTests on roslyn5.9 and roslyn4.8: 11/11 passed on each.