Export (0) Print
Expand All

Remove empty finalizers

This warning is supported in the stand-alone version of FxCop only. It is not supported in Code Analysis, which is integrated into Visual Studio.

TypeName

RemoveEmptyFinalizers

CheckId

CA1821

Category

Microsoft.Performance

Breaking Change

NonBreaking

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

Whenever you can, avoid finalizers because of the additional performance overhead involved in tracking object lifetime. The garbage collector will run the finalizer before collecting the object. This means that two collections will be required to collect the object. An empty finalizer incurs this added overhead without any benefit.

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

Do not exclude a message from this rule. Failure to suppress finalization degrades performance and provides no benefits.

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.

using System.Diagnostics;

    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.
        ~Class1()
        {
            Debug.Fail("Finalizer called!");
        }
#endif
    }

Community Additions

ADD
Show:
© 2014 Microsoft