The Use of Using statement in C#

After reading the topic heading many readers will refer the using keyword which is use in the top of the code in C# some thing like this 

using system.Data;

But right now i am referring to another using statement which is also the part of C#. The syntax of this statement is some thing like this 

using (var conn = new SqlConnection("connection string"))
{
   conn.Open();

    // execute sql statement here on the connection you created
}

This statement is use in place of a try catch statement where you may need to add a try block and a catch block. So instead of these two statements the using statement automatically calls IDesposible method after the work is done on a resource it also automatically closes the connection even when there is an exception which  means it also removes the extra code used for finally statement.

 
 if (myRes!= null)
            // Call the object's Dispose method.
            ((IDisposable)myRes).Dispose();
Advertisements

One thought on “The Use of Using statement in C#

  1. Have you ever considered about adding a little bit more than just your articles?
    I mean, what you say is valuable and everything.
    But imagine if you added some great images or videos to
    give your posts more, “pop”! Your content is
    excellent but with pics and clips, this site could certainly be one of the very best in its field.

    Great blog!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s