CA2216: Disposable types should declare finalizer

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 DisposableTypesShouldDeclareFinalizer
CheckId CA2216
Category Microsoft.Usage
Breaking Change Non Breaking

Cause

A type that implements System.IDisposable, and has fields that suggest the use of unmanaged resources, does not implement a finalizer as described by System.Object.Finalize.

Rule Description

A violation of this rule is reported if the disposable type contains fields of the following types:

How to Fix Violations

To fix a violation of this rule, implement a finalizer that calls your Dispose method.

When to Suppress Warnings

It is safe to suppress a warning from this rule if the type does not implement IDisposable for the purpose of releasing unmanaged resources.

Example

The following example shows a type that violates this rule.

using System;  
using System.Runtime.InteropServices;

namespace UsageLibrary
{
    public class  DisposeMissingFinalize :IDisposable
    {
        private bool disposed = false;
        private IntPtr unmanagedResource;
        
        [DllImport("native.dll")]
        private static extern IntPtr AllocateUnmanagedResource();
        
        [DllImport("native.dll")]
        private static extern void FreeUnmanagedResource(IntPtr p);
        
        DisposeMissingFinalize()
        {
            unmanagedResource = AllocateUnmanagedResource();
        }
        
        protected virtual void Dispose(bool disposing) 
        {
            if (!disposed) 
            {
                // Dispose of resources held by this instance.
                FreeUnmanagedResource(unmanagedResource);
                disposed = true;
   
                // Suppress finalization of this disposed instance.
                if (disposing)
                {
                    GC.SuppressFinalize(this);
                }
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }

        // Disposable types with unmanaged resources implement a finalizer.
        // Uncomment the following code to satisfy rule:
        //  DisposableTypesShouldDeclareFinalizer
        // ~TypeA()
        // {
        //     Dispose(false);
        // }
    }
}

CA2115: Call GC.KeepAlive when using native resources

CA1816: Call GC.SuppressFinalize correctly

CA1049: Types that own native resources should be disposable

See Also

System.IDisposable System.IntPtr System.Runtime.InteropServices.HandleRef System.UIntPtr System.Object.Finalize Dispose Pattern