How should a sealed C# class that creates and keeps its own FileStream and database connection implement IDisposable?
answer
- whoever creates it owns it
- cascade the call to owned fields
- safe to call twice
- throw helper after disposal
- no finalizer for managed fields
basics
~20 sThe class implements IDisposable, and its Dispose disposes the fields it created, returns early on a second call, and makes later member calls throw ObjectDisposedException. Being sealed with only managed fields, it needs no finalizer and no Dispose(bool).
solid answer
~40 sA class that creates disposable objects and stores them in fields owns them, so it implements `IDisposable` and cascades: `Dispose()` calls `Dispose()` on each owned field, conventionally in reverse order of creation. It must be idempotent, so a `_disposed` flag makes the second call return immediately, and public members guard with `ObjectDisposedException.ThrowIf(_disposed, this)` (.NET 7 and later) so a use after disposal fails clearly. Because the class is sealed and holds only managed objects, which take care of their own unmanaged handles, it needs no finalizer, no `protected virtual Dispose(bool)` and no `GC.SuppressFinalize`. The constructor deserves care too: if the connection fails to open after the file was created, dispose the file before rethrowing. Analyzer rule CA2213 reports an owned disposable field that `Dispose` never disposes.
code
csharp · 41 linesstring path = Path.Combine(Path.GetTempPath(), "q3-report.csv");
var report = new ReportGenerator(path);
report.WriteRow("id,total");
report.Dispose();
report.Dispose(); // idempotent: the second call does nothing
try { report.WriteRow("1,10"); }
catch (ObjectDisposedException ex) { Console.WriteLine(ex.Message); }
sealed class ReportGenerator : IDisposable
{
private readonly FileStream _file;
private readonly AuditConnection _connection;
private bool _disposed;
public ReportGenerator(string path)
{
_file = new FileStream(path, FileMode.Create);
try { _connection = new AuditConnection(); }
catch { _file.Dispose(); throw; }
}
public void WriteRow(string row)
{
ObjectDisposedException.ThrowIf(_disposed, this);
_file.Write(System.Text.Encoding.UTF8.GetBytes(row + "\n"));
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_connection.Dispose();
_file.Dispose();
}
}
// Stand-in for a database connection the class opens itself.
sealed class AuditConnection : IDisposable
{
public void Dispose() => Console.WriteLine("connection closed");
}go deeper
Recall that a class owning disposable fields implements IDisposable and disposes them in its own Dispose method.
Explain idempotence, the ObjectDisposedException.ThrowIf guard from .NET 7, and why a sealed managed-only class skips the finalizer and Dispose(bool).
Show the constructor that fails halfway, concurrent Dispose calls, and how CA2213 catches a field that was never disposed.
Decide which types are sealed by default, since that choice determines whether every disposable type must carry the Dispose(bool) extension hook.
## Ownership decides who implements IDisposable A **disposable object** is one whose type implements `IDisposable`; calling `Dispose()` releases what it holds, such as a file handle or a pooled network connection. The rule the .NET documentation gives is about **ownership**: a class that instantiates a disposable object and stores it in a field is typically responsible for its cleanup, so the class itself should implement `IDisposable` and pass the call on. This is called **cascading dispose**. The docs add the converse: a class that holds a disposable field but does **not own it** (it was handed the object by someone else) does not need to implement `IDisposable` for that field. Take a report generator that opens its own output file and its own connection for audit records. It created both, so it owns both. ## The shape of Dispose for a sealed owner ```csharp public void Dispose() { if (_disposed) return; _disposed = true; _connection.Dispose(); _file.Dispose(); } ``` Four properties make it correct: 1. **It disposes every owned field.** Forgetting one is the classic bug; CA2213, "Disposable fields should be disposed", reports a field assigned a locally created disposable object that `Dispose` never disposes. 2. **It is idempotent.** The documentation says a `Dispose` method should be callable multiple times without throwing, and later calls should do nothing. Callers, `using` statements and containers can easily dispose twice. 3. **It disposes in reverse order of creation** as a convention, mirroring how nested `using` declarations behave, so nothing is disposed while an object created after it may still use it. 4. **It does not throw** in normal operation, because an exception from cleanup can hide the exception that caused the cleanup. ## After disposal: ObjectDisposedException Once disposed, the object should refuse work rather than fail obscurely inside a closed stream. `ObjectDisposedException.ThrowIf(bool condition, object instance)`, added in .NET 7, is the throw helper for this: ```csharp public void WriteRow(string row) { ObjectDisposedException.ThrowIf(_disposed, this); // ... } ``` It throws `ObjectDisposedException` (a subclass of `InvalidOperationException`) whose message names the instance's type. An overload takes a `Type` instead of an instance. Analyzer rule CA1513 suggests replacing a hand-written `if (_disposed) throw new ObjectDisposedException(...)` with the helper. ## What a sealed, managed-only owner does not need | Piece | Needed here? | Why | |---|---|---| | `Dispose()` | Yes | The `IDisposable` contract | | Finalizer (`~ReportGenerator()`) | No | The class holds no raw unmanaged handle; `FileStream` already guards its own handle | | `protected virtual void Dispose(bool)` | No | The class is sealed, so no derived class needs a hook | | `GC.SuppressFinalize(this)` | No | With no finalizer the call has no effect; CA1816 asks for it only in unsealed types | The documentation's guidance is that a finalizer is required only when a type directly references unmanaged resources, and even then a `SafeHandle` is recommended instead. An unsealed class is different: it should offer the `Dispose(bool)` hook so a subclass can add its own cleanup. ## The constructor is part of the job A constructor that acquires two resources can fail halfway: ```csharp public ReportGenerator(string path) { _file = new FileStream(path, FileMode.Create); try { _connection = OpenAuditConnection(); } catch { _file.Dispose(); throw; } } ``` If the connection cannot be opened, the caller never receives an object, so it can never call `Dispose()`; without the `catch`, the file handle would stay open until finalization. ## Checking the implementation A disposable type is easy to test, and the tests document the contract for the next maintainer: - call `Dispose()` twice and assert that nothing throws and the owned objects were disposed once; - call a public member after disposal and assert `ObjectDisposedException`; - make the second resource's acquisition fail and assert the first one was released. Analyzer rule CA2213 is not enabled by default in .NET 10, so a project that wants the field check must turn it on; once it is on, a newly added field that `Dispose()` forgets is reported at build time instead of in a leak investigation. ## Common mistakes - Implementing `IDisposable` but disposing only some fields. - Adding a finalizer "to be safe", which makes every instance more expensive to collect and runs cleanup code at an unpredictable time. - Disposing a stream the class was given by its caller, which closes something the class does not own. - Calling members of owned fields from a finalizer: by then those objects may already have been finalized.
- The class is later unsealed so other teams can derive from it. What changes?It should follow the basic dispose pattern: a public non-virtual `Dispose()` that calls `Dispose(true)` and `GC.SuppressFinalize(this)`, and a `protected virtual void Dispose(bool disposing)` holding the cleanup, which a derived class overrides and chains with `base.Dispose(disposing)`. CA1063 and CA1816 check that shape. It still needs no finalizer unless it holds a raw unmanaged handle.
- Two threads may call Dispose() at the same time. Is the bool flag enough?No: both can read `false` before either writes `true`, and both dispose the fields. If concurrent disposal is possible, set the flag atomically, for example `if (Interlocked.Exchange(ref _disposed, 1) != 0) return;` with an `int` field. Most types document that they are not thread-safe and leave this to callers.
- Why is `ObjectDisposedException.ThrowIf(_disposed, this)` preferred over writing the throw by hand?It is shorter and keeps the throw out of the calling method, which helps small members stay inlinable; CA1513 suggests it for that reason. The helper is marked so it does not appear in the stack trace, and its `[DoesNotReturnIf(true)]` annotation tells nullable analysis that code after it runs only when the condition was false.
- Every class that implements IDisposable needs a finalizer
- Calling Dispose twice should throw ObjectDisposedException
- A class should dispose every disposable it holds, including ones it was given
- GC.SuppressFinalize frees the object's memory immediately
- A failed constructor is cleaned up by the caller's using statement