top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

What is the use of using statement in C#?

+4 votes
79 views
What is the use of using statement in C#?
posted Nov 13, 2013 by Atul Mishra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

When you are using an object that encapsulates any resource, you have to make sure that when you are done with the object, the object's Dispose method is called. This can be done more easily using the using statement in C#. The using statement simplifies the code that you have to write to create and then finally clean up the object. The using statement obtains the resource specified, executes the statements and finally calls the Dispose method of the object to clean up the object.

answer Nov 13, 2013 by Meenal Mishra
0 votes

The using statement is mostly used when you need to one or more resources in a segment. The using statement obtains one or various resources, executes them and then releases the objects or resources. It is widely used in database connectivity through C#.

using System;

namespace Using_Statement
{
  class check_using : IDisposable
   {
     public void Dispose()
      {
        Console.WriteLine("Execute  Second");
      }
   }

  class Program
   {       
     static void Main(string[] args)
      {
        using(check_using c=new check_using())
         {
           Console.WriteLine("Executes First");
         }
        Console.WriteLine("Execute Third");
        Console.ReadLine();
      }
   }
}

In the above example, the using statement calling the check_using class to execute. So, it first executes the using block, then executes the check_using class and finally executes the last statements.

Output

Executes First 
Execute  Second 
Execute Third 
answer Nov 20, 2014 by Manikandan J
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...