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

Objects should not be disposed more than once

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Refactor this code to make sure Dispose is only called once with this object.
    • Highlighting:
      Hide

      Primary: Second dispose or using
      Secondary: Previous dispose or using

      Show
      Primary: Second dispose or using Secondary: Previous dispose or using
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      C#
    • Irrelevant for Languages:
      ABAP, C, C++, Cobol, CSS, Flex, HTML, Java, JavaScript, Objective-C, PHP, PL/I, PL/SQL, Python, RPG, Swift, T-SQL, VB.Net, VB6, XML
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      10min
    • Analysis Scope:
      Main Sources, Test Sources
    • FxCop:
      DoNotDisposeObjectsMultipleTimes, CA2202

      Description

      Disposing an object twice, either with the using keyword or by calling Dispose directly, in the same method is at best confusing and at worst error-prone. The next developer might see only one of the Dispose/using and try to use an already-disposed object.

      In addition, even if the documentation of Disposable explicitly states that calling the Dispose method multiple times should not throw an exception, some implementation still do it. Thus it is safer to not dispose an object twice when possible.

      This rule raises an issue when, in the same method, the Dispose method is explicitly called twice on the same object, or when using is used with a direct call to Dispose().

      Noncompliant Code Examples

      using (var d = new Disposable()) // Noncompliant
      {
          d.Dispose();
      }
      
      using var d = new Disposable();
      d.Dispose(); // Noncompliant {{Refactor this code to make sure 'd' is disposed only once.}}
      

      Compliant Solution

      using var d = new Disposable();
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              jeanchristophe.collet Jean-Christophe Collet (Inactive)
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: