C# IDisposable and using: A Practical Guide
Some .NET objects own resources that should be released promptly, such as file handles, database connections, streams, and other unmanaged or disposable resources. C# provides IDisposable and using to make that cleanup predictable.
๐งน What Is IDisposable?
IDisposable defines a Dispose() method:
public interface IDisposable
{
void Dispose();
}
A disposable object can release resources when it is no longer needed.
๐ The Traditional using Statement
using (var stream = File.OpenRead("data.txt"))
{
// Use the stream here
}
When execution leaves the using block, the compiler-generated cleanup calls Dispose(), including when an exception occurs.
โจ Using Declarations
Modern C# also supports a shorter form:
using var stream = File.OpenRead("data.txt");
// Use the stream
// Dispose happens when the enclosing scope ends.
This can make methods involving several disposable objects much easier to read.
โ ๏ธ Why Not Just Wait for Garbage Collection?
Garbage collection manages managed memory, but many objects also hold external resources. Waiting for finalization can keep those resources occupied longer than necessary.
For example, a database connection should normally be closed promptly instead of relying on eventual garbage collection.
๐๏ธ Common IDisposable Examples
FileStreamStreamReaderStreamWriterSqlConnection- Many HTTP, database, and framework resource types
๐งฉ Creating Your Own Disposable Type
public sealed class ReportExporter : IDisposable
{
public void Dispose()
{
// Release resources here.
}
}
Consumers can then use:
using var exporter = new ReportExporter();
๐ง The Practical Rule
If an object implements IDisposable and you own its lifetime, make sure its disposal is handled correctly.
For more C# topics, continue to ๐ป C# Tutorials.
Ask AlgoLassi and get an answer plus the tutorials worth studying next.
๐ฌ Comments
Sign in with Google to publish immediately, or comment anonymously and wait for approval.
Comments will appear here when available.