Fix the MA0082 code fix for operands of another type or nullable operands
Merged
ME
2mo ago+126+126+012345678901234567890123456789-2-2-0123456789
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
IsNaNis now called on the type used by the comparison, which is the converted type of theNaNoperand withoutNullable<T>. SodoubleValue == float.NaNbecomesdouble.IsNaN(doubleValue)andfloatValue != double.NaNbecomes!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 withNaNis alwaysfalse(!=is alwaystrue).double.IsNaN(value.GetValueOrDefault())istrueonly 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 beforeRegisterCodeFix, 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_NullableOperandandComparisons_UserDefinedOperator_NoCodeFix. The first two failed before the fix. - Ran
DoNotNaNInComparisonsAnalyzerTestson roslyn5.9 and roslyn4.8: 11/11 passed on each.