liveBook · Manning

IDisposable

As explained in .NET in Action, Second Edition

IDisposable is a .NET interface for types that expose deterministic release of unmanaged or other disposable resources.

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

How .NET in Action, Second Edition covers it

How deep it goes
Explains Dispose, exception-safe cleanup, using syntax, and ownership decisions, but defers implementing the dispose pattern.
Examples
Demonstrates StreamReader cleanup, file input and output streams, StreamWriter, and JsonDocument during JSON processing.
What it assumes
Assumes familiarity with C# blocks, exceptions, streams, and garbage collection while teaching IDisposable and using from practical examples.
What you can do after
Operate disposable .NET resources safely with using declarations, explicit finally cleanup, and deliberate stream-ownership choices.
How it connects
Connects IDisposable to garbage collection, unmanaged resources, exception handling, streams, JSON parsing, and the dispose pattern.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.