Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
Previous Versions
.NET Framework 3.0
Tools
Development Tools
FxCop
FxCop Warnings
Usage Warnings
 Disposable types should declare fin...

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
Visual Studio Team System
Disposable types should declare finalizer

TypeName

DisposableTypesShouldDeclareFinalizer

CheckId

CA2216

Category

Microsoft.Usage

Breaking Change

NonBreaking

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.

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

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

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

The following example shows a type that violates this rule.

C#
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);
        // }
    }
}
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker