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.
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.
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.
Implementation of IDisposable interface
Lets evaluate in each scenario how our code works!
- Developer uses try-catch-finally approach
- Developer uses Using block
- Developer not uses either of the approach
With Try-Catch-Finally approach
With Using block approach
Developer not uses either of the approach