diff --git a/analyzers/src/SonarAnalyzer.CSharp/Rules/SillyMathematicalComparison.cs b/analyzers/src/SonarAnalyzer.CSharp/Rules/SillyMathematicalComparison.cs index 9f42bb27b65..a203684ea83 100644 --- a/analyzers/src/SonarAnalyzer.CSharp/Rules/SillyMathematicalComparison.cs +++ b/analyzers/src/SonarAnalyzer.CSharp/Rules/SillyMathematicalComparison.cs @@ -72,7 +72,8 @@ private static bool TryGetConstantValue(SemanticModel model, BinaryExpressionSyn // 'char' needs to roundtrip {{char -> int -> double}}, can't go {{char -> double}} private static bool TryConvertToDouble(object constant, out double typedConstant) => - ConversionHelper.TryConvertWith(constant is char ? Convert.ToInt32(constant) : constant, Convert.ToDouble, out typedConstant); + ConversionHelper.TryConvertWith(constant is char ? Convert.ToInt32(constant) : constant, Convert.ToDouble, out typedConstant) + && !double.IsInfinity(typedConstant); private static ValuesRange? TryGetRange(ITypeSymbol typeSymbol) => typeSymbol switch diff --git a/analyzers/tests/SonarAnalyzer.UnitTest/TestCases/SillyMathematicalComparison.cs b/analyzers/tests/SonarAnalyzer.UnitTest/TestCases/SillyMathematicalComparison.cs index 238e34dcd72..74a0482e5a0 100644 --- a/analyzers/tests/SonarAnalyzer.UnitTest/TestCases/SillyMathematicalComparison.cs +++ b/analyzers/tests/SonarAnalyzer.UnitTest/TestCases/SillyMathematicalComparison.cs @@ -453,5 +453,44 @@ public void ConstantInBothOperands() _ = 42f != double.MaxValue; // Compliant _ = 42f <= double.MaxValue; // Compliant } + + public void Edgecases() + { + const float fPositiveInfinity = float.PositiveInfinity; + const float fNegativeInfinity = float.NegativeInfinity; + const double dPositiveInfinity = double.PositiveInfinity; + const double dNegativeInfinity = double.NegativeInfinity; + + const float fNan = float.NaN; + const double dNan = double.NaN; + + float f = 42; + + _ = f <= fPositiveInfinity; // Compliant + _ = fNegativeInfinity < f; // Compliant + + _ = fNegativeInfinity != f; // Compliant + _ = dNegativeInfinity == f; // Compliant + + _ = f >= dPositiveInfinity; // Compliant + _ = dNegativeInfinity > f; // Compliant + _ = f != fPositiveInfinity; // Compliant + _ = f == dPositiveInfinity; // Compliant + + + _ = f == fNan; // Compliant + _ = f != fNan; // Compliant + _ = f <= fNan; // Compliant + _ = f >= fNan; // Compliant + _ = f > fNan; // Compliant + _ = f < fNan; // Compliant + + _ = dNan == f; // Compliant + _ = dNan != f; // Compliant + _ = dNan <= f; // Compliant + _ = dNan >= f; // Compliant + _ = dNan > f; // Compliant + _ = dNan < f; // Compliant + } } }