IDisposable interface

Many times, it happens that we need to implement IDisposable interface in our class. E.g. we have created a class and this class has some managed resources as well as some unmanaged resources. Now, in our whole project, all other classes / services started to consume this class. After consuming of a class, its responsibility of developer to release / dispose consumed objects.

How can we dispose object?

There are couple of ways by which developer can dispose an object.

1. Try-catch-finally

In finally block, developer will dispose the object no matter whether any exception occurred or not in try block.

TryCatchFinally

2. Using block

There is an Using block in which developer can initialize and use object. After completion of this block / when object goes out of scope, Dispose() method will be automatically called and object will be disposed.

Using

But what if developer forgot to use either of approach. Our managed resources will be disposed when garbage collector will run but what about unmanaged resources like COM component. So now it is our class responsibility to dispose unmanaged resources and at that time,  we should implement IDisposable interface.

Finalizers

Finalizers are like destructors. Whenever our object goes out of scope, finalizers will be called automatically. Generally, we don’t need to implement finalizer but when we are planning to implement IDisposable then we also need to implement Finalizer in our class.

Finalizer

Implementation of IDisposable interface

First
second
Third

Lets evaluate in each scenario how our code works!

  1. Developer uses try-catch-finally approach
  2. Developer uses Using block
  3. Developer not uses either of the approach

With Try-Catch-Finally approach

TryCatchFinallyWithIDisposable_Code
TryCatchFinallyWithIDisposable

With Using block approach

Using_Code
TryCatchFinallyWithIDisposable

Developer not uses either of the approach

FinallizerApproach
FinalizerCalled

Leave a Reply

Your email address will not be published. Required fields are marked *