IDisposable is a .NET interface for types that expose deterministic cleanup through one method, Dispose. It matters when an object holds a file handle or another resource that garbage collection may not release promptly. The dispose pattern provides a predictable boundary for releasing such resources. section 4.1.4
Use IDisposable resources with these practices:
- Call Dispose even when an operation throws; a finally block can safely use reader?.Dispose(). section 4.1.4
- Prefer a using block or using declaration, which invokes Dispose automatically at the end of its scope. section 4.1.4
- Check ownership when passing streams to methods: StreamWriter disposes its underlying stream by default, while JsonDocument.Parse does not close its input stream. section 4.2.1
Listing 4.12 Call Dispose even in the case of an exception
var reader = file.OpenText();
try
{
while ((line = reader.ReadLine()) != null); #1
}
finally
{
reader?.Dispose();
}
This listing shows the explicit cleanup pattern that using replaces, including disposal when reading fails. section 4.1.4
Scoped file and JSON processing
A command-line JSON processor opens input and output streams with using declarations, then creates a StreamWriter and JsonDocument with using as well. The writer uses leaveOpen: true so disposing the writer does not close the caller-owned output stream. Each disposable object is released when its enclosing scope ends. section 4.2.1
