Using statement vs Using Directive

Recently in a quiz, I came across a question about the “using” statement in relation with garbage collection. I was sure that using had nothing to do beyond specifying the namespace that a class used.
All I could think of was this
For eg : using System.Text;

However, a few days later, when I did a quick walkthrough of some code that was in front of me, I remembered that we use “using” within the code we write as in
using (Font font1 = new Font("Arial", 10.0f))
{
//some code related to font1
}
So I did some probing into MSDN and code project and here are the results:
What exactly do both the using’s do?
1. Using directive
First of all the using used with the namespace is called “using directive” (Many of you may know this, but I was not aware of this even after 3 yrs of coding in .NET). It does nothing more than suggesting which namespace (both user defined and system defined) is going to be used by the class.

2. Using statement
This can be a powerful tool to help in releasing memory – it specifies when the objects using the resources (for e.g. the object that uses font1 in the example above) should release them.
Have a look at this fragment of code:
 using (Font font1 = new Font("Arial", 10.0f))
{
               Console.WriteLine(font1.Name);
}
 
How does this block of code work?
Internally using statement calls a try and a finally block without catch. It uses IDisposable interface to free the memory allocated. The sequence is as follows:
1)      The constructor of Font1 is called i.e. (new Font("Arial", 10.0f)))
                                    |
            2) A try block with Console.WriteLine stmt is executed i.e. (Console.WriteLine(font1.Name);)
                                    |
3)The finally block disposes the memory allocated to the object font1 i.e. (font1.Dispose())
So the code essentially (that goes on within) would look like this:
private static void Main(string[] args)
{
      Font font1 = new Font ("Arial", 10.0f));
      try
      {
            Console.WriteLine(font1.Name);
      }
      finally
      {
            if (font1 != null)
            {
                  font1.Dispose();
            }
      }
 }

Hence, the using statement leaves it in the hands of the programmer to decide when memory should be freed. This would be otherwise done by the CLR.

First thing to be noted to use using statement : The class must implement IDisposable interface.

Another thing to be noted is that if any exception is thrown in step 1, then step 2 and 3 will be bypassed.

No comments:

Post a Comment