IDisposable
Learn to release unmanaged resources with IDisposable.
The IDisposable interface
The IDisposable interface contains a single method: Dispose(). It is used to release unmanaged resources such as files, sockets and database connections.
The GC cannot free these resources automatically, so the caller must invoke Dispose(). Making a class IDisposable says "close me when you are done". This lets the program show measurable, predictable resource behavior across long runs.
The Dispose pattern
When implementing IDisposable, the usual pattern is: call Dispose(true) to release resources, then GC.SuppressFinalize(this) to cancel the finalizer.
If you define a finalizer (~Logger()), the GC will still release resources when not disposed. This is a safety net against unmanaged resource leaks and helps the code reclaim its resources even under unexpected conditions.
Exercise Add Dispose to the Logger class
The Logger class implements IDisposable. Add a public void Dispose() method whose body writes Console.WriteLine("Closed");. In Main use using var l = new Logger();.
Show example solution
using var l = new Logger();
Example solution:
using System;
class Logger : IDisposable
{
public void Dispose()
{
Console.WriteLine("Closed");
}
}
class Program
{
static void Main()
{
using var l = new Logger();
}
}
Test yourself
-
Complete the Dispose method
public void ____() { _handle.Close(); }Show answer
public void Dispose() { _handle.Close(); } -
Which resource does IDisposable release?
- Unmanaged resources (file, socket)
- Only strings
- Only managed arrays
- Threads
Show answer
Unmanaged resources (file, socket) — Correct. IDisposable is for unmanaged resources like files and sockets.
-
Resource management matches
- IDisposable
- Dispose() method
- GC.SuppressFinalize
- Cancels the finalizer
- ~Logger()
- Finalizer (destructor)
- using
- Automatic Dispose