All rules
CA1816Usage Enabled by default: As suggestion MS default: Warning

Call GC.SuppressFinalize correctly

Call `GC.SuppressFinalize(this)` in Dispose implementations.

Microsoft docs

Description

Dispose methods should call GC.SuppressFinalize so the object is not finalized unnecessarily.

Cause

Violations of this rule can be caused by:

  • In an unsealed class, a method that's an implementation of System.IDisposable.Dispose and doesn't call System.GC.SuppressFinalize.
  • A method that's not an implementation of System.IDisposable.Dispose and calls System.GC.SuppressFinalize.
  • A method that calls System.GC.SuppressFinalize and passes something other than this (C#) or Me (Visual Basic).

Why it matters

Suppressing finalization after disposal avoids the cost of running the finalizer on an already-cleaned object.

How to fix violations

To fix a violation of this rule:

  • If the method is an implementation of System.IDisposable.Dispose, add a call to System.GC.SuppressFinalize.
  • If the method is not an implementation of System.IDisposable.Dispose, either remove the call to System.GC.SuppressFinalize or move it to the type's System.IDisposable.Dispose implementation.
  • Change all calls to System.GC.SuppressFinalize to pass this (C#) or Me (Visual Basic).
  • If the type is not meant to be overridden, mark it as sealed.

Examples

Avoid
public void Dispose()
{
    _handle.Close();
}
Prefer
public void Dispose()
{
    _handle.Close();
    GC.SuppressFinalize(this);
}

When to suppress

Only suppress a warning from this rule if you're deliberately using System.GC.SuppressFinalize to control the lifetime of other objects. Don't suppress a warning from this rule if an implementation of System.IDisposable.Dispose doesn't call System.GC.SuppressFinalize. In this situation, failing to suppress finalization degrades performance and provides no benefits.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0