Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-2291

Overflow checking should not be disabled for "Enumerable.Sum"

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Refactor this code to handle "OverflowException".
    • Default Severity:
      Critical
    • Impact:
      High
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      C#
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      15min
    • Analysis Scope:
      Main Sources
    • ReSharper:
      EnumerableSumInExplicitUncheckedContext

      Description

      Enumerable.Sum() always executes addition in a checked context, so an OverflowException will be thrown if the value exceeds MaxValue even if an unchecked context was specified. Using an unchecked context anyway represents a misunderstanding of how Sum works.

      This rule raises an issue when an unchecked context is specified for a Sum on integer types.

      Noncompliant Code Example

      void Add(List<int> list)
      {
        int d = unchecked(list.Sum());  // Noncompliant
      
        unchecked 
        {
          int e = list.Sum();  // Noncompliant
        }
      }
      

      Compliant Solution

      void Add(List<int> list)
      {
        int d = list.Sum();
      
        try 
        {
          int e = list.Sum();
        } 
        catch (System.OverflowException e) 
        {
          // exception handling...
        }
      }
      

      Exceptions

      When the Sum() call is inside a try-catch block, no issues are reported.

      void Add(List<int> list)
      {
        unchecked 
        {
          try 
          {
            int e = list.Sum();
          } 
          catch (System.OverflowException e) 
          {
            // exception handling...
          }
        }
      }
      

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            ann.campbell.2 Ann Campbell
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Dates

              Created:
              Updated: