Member-only story
IDisposable in C#

In C#, IDisposable
is an interface that provides a mechanism to release unmanaged resources explicitly. It's particularly useful when dealing with resources such as file handles, database connections, network connections, or any resource that is not managed by the .NET runtime's garbage collector.
Purpose of IDisposable
The primary purpose of IDisposable
is to clean up resources that are not automatically managed by the garbage collector, which only manages memory allocated by the .NET runtime itself (managed resources).
Examples of unmanaged resources include:
- File handles and streams
- Database connections
- Network sockets
- COM objects
- Handles to operating system resources
When a class implements IDisposable
, it promises that it has resources that need to be explicitly released. The Dispose
method should be implemented to release these resources. This method can be called explicitly by user code or can be invoked automatically using the using
statement.
The using
statement ensures that the Dispose
method is called on an object that implements IDisposable
, even if an exception occurs. It simplifies the code for managing resources and helps avoid resource leaks.