dotnet / dotnet/docs

Documentation for CA2215 is vague and inconsistent.

Open
#27,818 0 comments 0 reactions 0 assignees View on GitHub
dotnet-fundamentals/svc
Dominant language
No language data
Stars
4.8k
Forks
6.1k
Avg merge
19h 10m
Merged PRs (30d)
268

Description

I'd propose the following code sample in lieu of the sample on the page.

```
using System;

namespace ca2215
{
public abstract class AbstractBase : IDisposable
{
bool _disposed;
protected virtual void Dispose(bool disposing) //Dispose is virtual, so Derived.Dispose() will always be called if defined.
{
if (disposing)
{
// Dispose managed resources
}

// Free native resources

_disposed = true;
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

// Disposable types implement a finalizer.
~AbstractBase()
{
Dispose(false);
}
}

public class Derived : AbstractBase //Derived type inherits IDisposable interface
{
bool _disposed; //private variable scoped to Derived class. Enables out-of-order disposal (base first or derived first)

protected override void Dispose(bool disposing)
{
if (_disposed) { return; }

if (disposing)
{
// Dispose managed resources specific to the Derived type
}

// Free native resources specific to the Derived type

_disposed = true;

base.Dispose(true);
}
}
}
```

Perhaps even better would be to piece together the sample code for [https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose#the-disposebool-method-overload](url) and the sample code for [https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose#implement-the-dispose-pattern-for-a-derived-class](url). Or just refer to these samples instead of maintaining another (imo poor) sample.

EDIT:Formatting.

---
#### Document Details

⚠ *Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.*

* ID: e4e8200c-6283-341c-28d6-889bc776b4de
* Version Independent ID: fd8cf98d-be1c-8265-a5c8-da1d17b29d1d
* Content: [CA2215: Dispose methods should call base class dispose (code analysis) - .NET](https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2215)
* Content Source: [docs/fundamentals/code-analysis/quality-rules/ca2215.md](https://github.com/dotnet/docs/blob/main/docs/fundamentals/code-analysis/quality-rules/ca2215.md)
* Product: **dotnet-fundamentals**
* GitHub Login: @gewarren
* Microsoft Alias: **gewarren**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.