Rediger

Del via


CA2216: Disposable types should declare finalizer

Property Value
Rule ID CA2216
Title Disposable types should declare finalizer
Category Usage
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 No

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.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA2216
// The code that's violating the rule is on this line.
#pragma warning restore CA2216

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA2216.severity = none

For more information, see How to suppress code analysis warnings.

Example

The following example shows a type that violates this rule.

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);
    // }
}

CA1816: Call GC.SuppressFinalize correctly

See also