The using statement is mostly used to handle any managed object that implements the IDisposable interface.
At that time, we use Structured Exception Handling to ensure that the Dispose() of IDisposable interface implemented in your class is called.
Let's look at an example.
Create New Project named "UseOfUsingKeyword" and create a new class that implements the IDisposable interface.
MyResourceClass.cs
- class MyResourceClass : IDisposable
- {
- public void Dispose()
- {
- Console.WriteLine("Releasing all the resources......");
- }
- public void DoSomeTask()
- {
- Console.WriteLine("Starting some task......");
- for (int i = 0; i < 10; i++)
- {
- Console.WriteLine("Doing some task.....");
- }
- }
- }
In the above class, we've implemented an IDisposable interface; the IDisposable interface contains only 1 Method as shown below.
The user should call this method when they finish with the object.
So, we designed our Dispose() method in our class to do the cleanup task. The DoSomeTask() method is performing some task.
The following is our Main() method, where we divided our code into 2 Cases.
Case I: Where, we release the resources manually.
Case II: Use of the using keyword to release resources automatically.
Program.cs
- class Program
- {
- static void Main(string[] args)
- {
- Console.Title = "Use of using Keyword";
-
- #region Case - I
- MyResourceClass ms1 = new MyResourceClass();
- try
- {
- ms1.DoSomeTask();
- }
- finally
- {
- ms1.Dispose();
- }
- #endregion
- #region Case - II
- using (MyResourceClass ms = new MyResourceClass())
- {
- ms.DoSomeTask();
- }
- #endregion
- Console.WriteLine();
- }
- }
In Case 1, we used Structured Exception Handling and called Dispose() in the finally block manually to release resources, because we know that the finally block always executes.
In Case 2, the using statement calls the MyResourceClass class to execute its task via DoSomeTask(). So, it first executes the using block, then after completion of the Task [DoSomeTask()], it'll automatically call the Dispose() and will release the resources.
Note: While Executing Case II, please comment Case I block and vice-a-versa
You'll get the same output for both cases, when you run the program.
The interesting part here is that when you look into the CIL code of the Main() using ildasm.exe tool, you'll see that the using syntax is expanded to try/finally logic and the Dispose() method is called. Please find the following for that.
Conclusion
using syntax does remove the need to manually wrap a disposable object within a try/finally block.
I hope this article helps you to understand the use of the using keyword in C#.
If there is any mistake in this article then please let me know. Please provide your valuable feedback and comments, which enable me to provide a better article the next time.