CA2215: Dispose methods should call base class dispose

Note

This article applies to Visual Studio 2015. If you're looking for the latest Visual Studio documentation, use the version selector at the top left. We recommend upgrading to Visual Studio 2019. Download it here

TypeName DisposeMethodsShouldCallBaseClassDispose
CheckId CA2215
Category Microsoft.Usage
Breaking Change Non Breaking

Cause

A type that implements System.IDisposable inherits from a type that also implements IDisposable. The Dispose method of the inheriting type does not call the Dispose method of the parent type.

Rule Description

If a type inherits from a disposable type, it must call the Dispose method of the base type from within its own Dispose method. Calling the base type method Dispose ensures that any resources created by the base type are released.

How to Fix Violations

To fix a violation of this rule, call base.Dispose in your Dispose method.

When to Suppress Warnings

It is safe to suppress a warning from this rule if the call to base.Dispose occurs at a deeper calling level than the rule checks.

Example

The following example shows a type TypeA that implements IDisposable.

using System;  

namespace UsageLibrary
{
    public class  TypeA :IDisposable
    {
     
        protected virtual void Dispose(bool disposing) 
        {
            if (disposing) 
            {
                // Dispose managed resources
            }

            // Free native resources
        }

        public void Dispose()
        {

                Dispose(true);

                GC.SuppressFinalize(this);

        }

        // Disposable types implement a finalizer.
        ~TypeA()
        {
            Dispose(false);
        }
    }
}

Example

The following example shows a type TypeB that inherits from type TypeA and correctly calls its Dispose method.

Imports System

Namespace UsageLibrary

  Public Class TypeB
      Inherits TypeA
   
      Protected Overrides Sub Finalize()
          Try
              Dispose(False)
          Finally
              MyBase.Finalize()
          End Try
      End Sub
   
  End Class
  
End Namespace

See Also

System.IDisposable Dispose Pattern