CA1001: Types that own disposable fields should be disposable

 

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

TypeNameTypesThatOwnDisposableFieldsShouldBeDisposable
CheckIdCA1001
CategoryMicrosoft.Design
Breaking ChangeNon-breaking - If the type is not visible outside the assembly.

Breaking - If the type is visible outside the assembly.

A class declares and implements an instance field that is a System.IDisposable type and the class does not implement IDisposable.

A class implements the IDisposable interface to dispose of unmanaged resources that it owns. An instance field that is an IDisposable type indicates that the field owns an unmanaged resource. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface. If the class does not directly own any unmanaged resources, it should not implement a finalizer.

To fix a violation of this rule, implement IDisposable and from the IDisposable.Dispose method call the Dispose method of the field.

Do not suppress a warning from this rule.

The following example shows a class that violates the rule and a class that satisfies the rule by implementing IDisposable. The class does not implement a finalizer because the class does not directly own any unmanaged resources.

using System;
using System.IO;
  
namespace DesignLibrary
{
   // This class violates the rule.
   public class NoDisposeMethod
   {
      FileStream newFile;

      public NoDisposeMethod()
      {
         newFile = new FileStream(@"c:\temp.txt", FileMode.Open);
      }
   }

   // This class satisfies the rule.
   public class HasDisposeMethod: IDisposable
   {
      FileStream newFile;

      public HasDisposeMethod()
      {
         newFile = new FileStream(@"c:\temp.txt", FileMode.Open);
      }

      protected virtual void Dispose(bool disposing)
      {
         if (disposing)
            {
               // dispose managed resources
               newFile.Close();
            }
          // free native resources
      }

      public void Dispose()
      {
         Dispose(true);
	     GC.SuppressFinalize(this);
      }
   }
}

CA2213: Disposable fields should be disposed

CA2216: Disposable types should declare finalizer

CA2215: Dispose methods should call base class dispose

CA1049: Types that own native resources should be disposable

Show: