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

Value
Rule ID CA2015
Category Reliability
Fix is breaking or non-breaking Non-breaking

Cause

Defining finalizers for types derived from MemoryManager<T>

Rule description

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

Note

The MemoryManager<T> class is intended for advanced scenarios. Most developers do not need to use it.

How to fix violations

To fix the violation, remove the finalizer definition.

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 fine to suppress a violation of this rule if the intent is to create a finalizer for debugging or validation purposes.

See also