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


๐Ÿงฉ 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.

๐Ÿค– AlgoLassi Assistant Have a question about this tutorial?

Ask AlgoLassi and get an answer plus the tutorials worth studying next.

Ask a question

๐Ÿ’ฌ Comments

Sign in with Google to publish immediately, or comment anonymously and wait for approval.

Comments will appear here when available.