LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
C# Programming

IDisposable, Using Statement and Resource Management

Applications use resources such as files, database connections, and network streams. These resources should be released when we finish using them. Otherwise, they may remain occupied longer than needed.

1Why Must We Release Resources?

Hi friends, in this article we will learn how C# handles resources such as files, streams and database connections. These resources are not managed like ordinary objects. IDisposable gives an object a standard way to release resources when we finish using it. The using statement helps us call that cleanup reliably, even when an exception occurs.

2Think About a Library Book

Imagine borrowing a book from a library. You use it and return it so another person can borrow it. A file or database connection is similar: your application takes ownership of a resource, uses it, and should release it promptly.

If the application forgets to close a file, other code may be unable to access it. A database connection left open can also reduce the connections available to other requests. Disposal is the act of giving those resources back.

3Understand the Three Main Ideas

IDisposable

IDisposable is an interface with one method: Dispose(). A class implements it when it needs to provide cleanup logic.

Using statement

A using statement creates a scope. When execution leaves that scope, C# calls Dispose(), including when an exception is thrown.

Using declaration

From C# 8, we can write using var. The resource is disposed at the end of the containing scope, rather than at the end of a separate block.

Approach When disposal happens
using (...) At the end of its block
using var At the end of the containing scope
Manual Dispose() Only when explicitly called
Remember Disposal is deterministic cleanup. Garbage collection does not guarantee that a file or connection is released at a particular time.

4Build a Small Disposable Resource

In this example, ReportWriter implements IDisposable. The using block guarantees that its cleanup method is called after the report is written.

Program.csC#
using System;

class ReportWriter : IDisposable
{
    public void WriteReport()
    {
        Console.WriteLine("Writing report...");
    }

    public void Dispose()
    {
        Console.WriteLine("Resource released.");
    }
}

class Program
{
    static void Main()
    {
        using (ReportWriter writer = new ReportWriter())
        {
            writer.WriteReport();
        }

        Console.WriteLine("Application finished.");
    }
}
Pro Tip Prefer using for disposable objects. It makes the cleanup path clear and protects against forgotten calls.

5Check the Console Result

The report is written first. When the using block ends, Dispose() runs. Only then does the final message appear.

Console Output
Writing report...
Resource released.
Application finished.
Common Mistake Do not assume that assigning null disposes an object. It only changes a reference; it does not call Dispose().

6Watch the Code Run Step by Step

The editor below reveals the source, enters the run command and displays the same output in execution order.

Program.cs - Visual Studio Code
 
Program.cs
1using System;
2
3class ReportWriter : IDisposable
4{
5 public void WriteReport()
6 {
7 Console.WriteLine("Writing report...");
8 }
9
10 public void Dispose()
11 {
12 Console.WriteLine("Resource released.");
13 }
14}
15
16class Program
17{
18 static void Main()
19 {
20 using (ReportWriter writer = new ReportWriter())
21 {
22 writer.WriteReport();
23 }
24
25 Console.WriteLine("Application finished.");
26 }
27}
PROBLEMSOUTPUTDEBUG CONSOLETERMINAL
PS C:\Projects\Demo> dotnet run
Writing report...
Resource released.
Application finished.
PS C:\Projects\Demo>
Ln 20, Col 9UTF-8C#Ready

7Keep These Points in Mind

Use IDisposable when an object owns resources that need explicit cleanup. Use a using statement or declaration so disposal happens at the correct scope boundary. This keeps file handles, streams and connections from being held longer than necessary.

  • Implement: Add Dispose() to types that own disposable resources.
  • Use: Wrap resource usage in a using scope.
  • Remember: Disposal and garbage collection are different responsibilities.

8Questions Interviewers May Ask

Q1Easy

What is IDisposable?

It is a .NET interface that defines the Dispose() method. Classes use it to release resources explicitly.

Q2Easy

Why do we use a using statement?

It ensures Dispose() is called when execution leaves the block, including when an exception occurs.

Q3Medium

Does Dispose() destroy an object?

It releases resources owned by the object. The object may remain in memory until it becomes unreachable and is collected.

Q4Medium

What is the difference between using statement and using declaration?

A using statement disposes at the end of its block. A using declaration disposes at the end of the containing scope.

Q5Hard

Is the garbage collector a replacement for Dispose()?

No. Garbage collection manages memory, while Dispose() releases resources at a predictable point. They solve different problems.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.