Open In App

IDisposable Interface in C#

Last Updated : 15 Sep, 2025
Comments
Improve
Suggest changes
1 Likes
Like
Report

The IDisposable interface in C# provides a standard way to release unmanaged resources like file handles, database connections, or network sockets.

Unlike destructors (which rely on garbage collection and are non-deterministic), IDisposable allows deterministic cleanup of resources at the exact time you want.

Syntax:

publi c interface IDisposable {

void Dispose();

}

  • Declared in the System namespace.
  • Contains a single method: Dispose().
  • Used to free unmanaged resources manually.
  • Often implemented with the using statement for automatic cleanup.
  • Preferred over destructors for reliability and better performance.

Key Methods

1. Public Dispose()

  • Called by the consumer of the class.
  • Invokes Dispose(bool disposing) and suppresses finalization (GC.SuppressFinalize).

2. Protected virtual Dispose(bool disposing)

  • Contains actual cleanup logic.
  • If disposing == true, release managed and unmanaged resources.
  • If disposing == false, release only unmanaged resources.

3. Boolean disposedValue

  • Prevents multiple calls to Dispose.

4. Destructor (optional)

  • Calls Dispose(false) to clean unmanaged resources if Dispose() was never called.

Example 1: Implementing IDisposable

C#
using System;
using System.IO;

class FileHandler : IDisposable {
    private StreamReader reader;

    public FileHandler(string path) {
        reader = new StreamReader(path);
        Console.WriteLine("File opened.");
    }

    public void ReadFile() {
        Console.WriteLine(reader.ReadLine());
    }

    // Implementation of Dispose method
    public void Dispose() {
        if (reader != null) {
            reader.Close();
            Console.WriteLine("File closed.");
        }
    }
}

class Program {
    static void Main() {
        FileHandler fh = new FileHandler("test.txt");
        fh.ReadFile();
        fh.Dispose(); // Explicit call
    }
}

Output:

File opened.

<First line of file>

File closed.

This program shows how to implement the IDisposable interface to clean up resources manually.

  • FileHandler class opens a file using StreamReader inside its constructor.
  • The Dispose() method closes the file and releases the resource.
  • In Main(), an object of FileHandler is created, the file is read, and then Dispose() is called explicitly to close the file.

This ensures the file handle is released immediately instead of waiting for the garbage collector.

Example 2: Using the using Statement

The using statement calls Dispose() automatically, even if an exception occurs.

C#
using System;
using System.IO;

class Program {
    static void Main() {
        using (StreamReader reader = new StreamReader("test.txt")) {
            Console.WriteLine(reader.ReadLine());
        } // Dispose() is called automatically here
    }
}

Best Practices

  • Always implement Dispose() in classes that use unmanaged resources.
  • Use the using statement whenever possible for automatic cleanup.
  • If your class owns other disposable objects, ensure they are disposed inside your Dispose() method.

Destructor vs IDisposable

FeatureDestructor (~ClassName)IDisposable.Dispose()
Who Calls It?Garbage CollectorProgrammer / using block
When Runs?Non-deterministicDeterministic (exact time)
Parameters AllowedNoYes (Dispose pattern can take flag)
Best ForRare unmanaged cleanupAll resource cleanup (recommended)
Suggested Quiz
3 Questions

The IDisposable interface is used to:

  • A

    Manage stack memory

  • B

    Release unmanaged resources deterministically

  • C

    Force garbage collection

  • D

    Track object generations

Explanation:


What is the advantage of using the using statement with IDisposable objects?

  • A

    It makes objects live longer

  • B

    It automatically calls Dispose() even on exceptions

  • C

    It disables GC

  • D

    It stores objects on the stack

Explanation:


Which statement is correct regarding Destructor (~ClassName) vs IDisposable.Dispose()?

  • A

    Destructor is deterministic, Dispose is non-deterministic

  • B

    Destructor is called by programmer, Dispose by GC

  • C

    Destructor is non-deterministic, Dispose is deterministic

  • D

    Both run at exact same time

Explanation:

Destructors depend on GC, while Dispose allows deterministic cleanup

Quiz Completed Successfully
Your Score :   2/3
Accuracy :  0%
Login to View Explanation
1/3 1/3 < Previous Next >

Article Tags :

Explore