Using using to dispose objects in .NET

In this article, I am going to explain how with the help of using keyword we can safely dispose objects in .NET applications.

As we know, we should derive from the IDisposable interface in .NET to clean up any unmanaged (or even managed, see this ) resources like database connections, sockets or windows handle that our objects are managing.

Let us create a sample application to demonstrate the concept. We will create a class called MyDisposableClass and derive it from the IDisposable interface. We need to implement the Dispose method and this is where we will clean up the unmanaged resources that MyDisposableClass is holding. We have added a couple of methods to our class which we are going to call at multiple places in the code.

Now, let us create an object of class MyDisposable and call the DoWork method. After that, we call OtherStuff to do something else, and then we call the DoSomeMoreWork method of MyDisposable object. Finally, we need to call the Dispose method to do the clean-up. We have also put all this code in a try-catch block to handle bad stuff from the code.

This will work just fine since we are calling Dispose method ourselves.

Application running

But what if some exception is thrown from OtherStuff? The execution will move to the catch block and the Dispose method will not be called resulting in a memory leak in case our object is managing unmanaged resources. Let us see it in action.

Dispose not called

There are a couple of ways to handle this scenario. We can call Dispose method in the catch block which is not such a good solution because then we will need to keep track of all such places in the code where those objects are going out of scope. The other better solution is to use using. Let us just add using where we are creating the object of MyDisposable class and remove the manual call to Dispose method.

Dispose called automatically

And as we can see, as soon as the object goes out of scope, the Dispose method is called automatically with the help of using keyword. Expectedly, this will hold true even if there is no exception thrown by the code.

Dispose called for normal flow

And this is the benefit of using using. Typically, we use using when our class is managing unmanaged resources which are not garbage collected and we need to dispose them manually. But this is helpful in the general scenarios as well when we need to keep track of objects going out of scope.

Hope this article is helpful in the understanding of using keyword.

Happy Coding!!!

Learning to be a perfect learner