using block in C#.Net

  • using block in C# ensures correct use of IDisposable interface.
  • We can use using block only on the objects that implements IDisposable interface.
  • using block calls the dispose method of an object in a correct way and it also causes the object to go out of scope when dispose method of that object gets called.
  • using block gets converted to try..finally block after getting compiled to MSIL code. You can check MSIL code using ILDASM tool.
  • using block ensures that dispose method gets called even if an exception occurs.
  • Multiple type can be declared in using statement.

See below code sample for the same.

+
Code

using System;
 
namespace using_block
{
    class Program
    {
        static void Main(string[] args)
        {
            using (clsUseByUsingBlock obj1 = new clsUseByUsingBlock())
            {
                obj1.num = 2;
            }
        }
    }
 
    class clsUseByUsingBlock:IDisposable
    {
        public int num { getset; }
 
        public void Dispose()
        {
           //Cleanup activities
        }
    }
}

In above code sample, we have declared a class clsUseByUsingBlock which implements dispose method of IDisposable interface. We are used object of this class in using block. So at the background using block automatically calls the dispose method of our class, we don't need to explicitly call this dispose method.

This using block gets converted to try..finally block once code gets compiled. See below code for the same with try..finally block.

+
Code

clsUseByUsingBlock obj2 = new clsUseByUsingBlock();
try
{
      obj2.num = 2;
}
finally
{
      obj2.Dispose();
}

When you check actual MSIL code using ILDASM tool, it looks like below.


using block in C#

No comments :