Alireza Farokhi
2 min readMay 9, 2022

What does IDisposable do in .Net

before we dive into, we need to know a little about garbage collection and Resource management.

Garbage Collector

The garbage collector (GC) in .NET is a core part of the .NET Common Language Runtime (CLR) and is available to all .NET programming languages. The GC was never meant to manage resources; it was designed to manage memory allocation, and it does an excellent job at managing memory allocated directly to native .NET objects. It was not designed to deal with unmanaged memory and operating system allocated memory, so it becomes the responsibility of the developer to manage these resources.

Resources in .Net are divided into 2 categories: Managed resources and Unmanaged resources.

Managed Resources

Managed resources are those that are pure .NET code and managed by the runtime and are under its direct control,And garbage collector can free up memory allocated by them automatically.

Unmanaged Resources

There are resources that the garbage collector is unable to free up memory allocated by them automatically, they include items such as streams, files, database, connections and … .

If you develop a class that owns unmanaged resources, you would normally include a finalizer or destructor, that release those resources when objects go out of scope.

How ever as the actual execution time of the finalizer is not predictable, the resource can stay allocated for longer than is desirable.

By implementing IDisposable interface, you allow the disposal of such resources to be requested immediately, rather than waiting for garbage collector.

IDisposable interface has a method called Dispose. Below is a sample implementation of this method:

SuppressFinalize informing the garbage collector (GC) that this object was cleaned up fully.

Below is complete sample:

More Detail:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Alireza Farokhi
Alireza Farokhi

No responses yet

Write a response