All rules
CA2213Usage Enabled by default: No

Disposable fields should be disposed

Disposable fields should be disposed

Microsoft docs

Description

A type is responsible for disposing of all its unmanaged resources. Rule CA2213 checks to see whether a disposable type (that is, one that implements System.IDisposable) T declares a field F that is an instance of a disposable type FT. For each field F that's assigned a locally created object within the methods or initializers of the containing type T, the rule attempts to locate a call to FT.Dispose. The rule searches the methods called by T.Dispose and one level lower (that is, the methods called by the methods called by T.Dispose). Other than the special cases, rule CA2213 fires only for fields that are assigned a locally created disposable object within the containing type's methods and initializers. If the object is created or assigned outside of type T, the rule does not fire. This reduces noise for cases where the containing type doesn't own the responsibility for disposing of the object.

Cause

A type that implements System.IDisposable declares fields that are of types that also implement System.IDisposable. The System.IDisposable.Dispose method of the field is not called by the System.IDisposable.Dispose method of the declaring type.

How to fix violations

To fix a violation of this rule, call System.IDisposable.Dispose on fields that are of types that implement System.IDisposable.

Example

protected virtual void Dispose(bool disposing)
{
   if (!disposed)
   {
      // Dispose of resources held by this instance.
      aFieldOfADisposableType.Dispose();

      disposed = true;

      // Suppress finalization of this disposed instance.
      if (disposing)
      {
          GC.SuppressFinalize(this);
      }
   }
}

When to suppress

It's safe to suppress a warning from this rule if:

  • The flagged type is not responsible for releasing the resource held by the field (that is, the type does not have *dispose ownership*)
  • The call to System.IDisposable.Dispose occurs at a deeper calling level than the rule checks
  • the dispose ownership of the field(s) is not held by the containing type.
Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0