Редагувати

Поділитися через


CA1821: Remove empty finalizers

Property Value
Rule ID CA1821
Title Remove empty finalizers
Category Performance
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 9 As suggestion

Cause

A type implements a finalizer that is empty, calls only the base type finalizer, or calls only conditionally emitted methods.

Rule description

Whenever you can, avoid finalizers because of the additional performance overhead that's involved in tracking object lifetime. The garbage collector runs the finalizer before it collects the object. This means that at least two collections are required to collect the object. An empty finalizer incurs this added overhead without any benefit.

How to fix violations

Remove the empty finalizer. If a finalizer is required for debugging, enclose the whole finalizer in #if DEBUG / #endif directives.

When to suppress warnings

Do not suppress a message from this rule.

Example

The following example shows an empty finalizer that should be removed, a finalizer that should be enclosed in #if DEBUG / #endif directives, and a finalizer that uses the #if DEBUG / #endif directives correctly.

    public class Class1
    {
        // Violation occurs because the finalizer is empty.
        ~Class1()
        {
        }
    }

    public class Class2
    {
        // Violation occurs because Debug.Fail is a conditional method.
        // The finalizer will contain code only if the DEBUG directive
        // symbol is present at compile time. When the DEBUG
        // directive is not present, the finalizer will still exist, but
        // it will be empty.
        ~Class2()
        {
            Debug.Fail("Finalizer called!");
        }
    }

    public class Class3
    {
#if DEBUG
        // Violation will not occur because the finalizer will exist and
        // contain code when the DEBUG directive is present. When the
        // DEBUG directive is not present, the finalizer will not exist,
        // and therefore not be empty.
        ~Class3()
        {
            Debug.Fail("Finalizer called!");
        }
#endif
    }