C#idiomatic C#
ca2015fundamentals/code-analysis/quality-rules

Code analysis

CA2015: Do not define finalizers for types derived from MemoryManager<T>

Learn about code analysis rule ca2015: Do not define finalizers for types derived from MemoryManager&lt;T&gt;

CA2015 Reliability enabled by default in .NET 10: As warning
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

Defining finalizers for types derived from System.Buffers.MemoryManager

Rule description

Adding a finalizer to a type derived from System.Buffers.MemoryManager is likely an indication of a bug, as it suggests a native resource that could have been handed out in a System.Span is getting cleaned up and potentially while it is still in use by the System.Span.

How to fix violations

To fix the violation, remove the finalizer definition.

csharp
class DerivedClass <T> : MemoryManager<T>
{
    public override bool Dispose(bool disposing)
    {
        if (disposing)
        {
            _handle.Dispose();
        }
    }

    ...

    // Violation occurs, remove the finalizer to fix the warning.
    ~DerivedClass() => Dispose(false);
}

When to suppress warnings

It is safe to suppress a violation of this rule if the intent is to create a finalizer for debugging or validation purposes.

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.

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

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

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

To disable this entire category of rules, set the severity for the category to none in the configuration file.

ini
[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Reliability.severity = none

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

See also