Home > .Net Technologies, C#/VB.Net, CodeProject, Dot Net Tips > Using Statement and Dispose Method in C# and VB.Net

Using Statement and Dispose Method in C# and VB.Net

Since .Net 2.0, we are aware of using statement to perform resource intensive operations like database operations, file IO operations, etc. Using statement basically marks a boundary for the objects specified inside using () braces. So when code block using (){} (in C#) or Using – End Using (in VB.Net) is exited either after normal execution or some exception cause, the framework invokes the Dispose method of these objects automatically. Before creating or using any object inside using block, one must make sure that the object type implements the IDisposable interface.
We can specify multiple objects inside using-block, and also write using-blocks in stack as shown in example below.
public class DotNetTips
private void DoSomeOperation()
using (SqlConnection con1 = new SqlConnection("First Connection String"), con2 = new SqlConnection(("Second Connection String"))
//Rest of the code goes here

private void DoSomeOtherOperation()
using (SqlConnection con = new SqlConnection("Connection String"))
using (SqlCommand cmd = new SqlCommand())
//Rest of the code goes here
Using statement is useful when we have to call dispose method multiple times on different objects. Otherwise, we will have to call Dispose method on each object as:
if (con != null) con.Dispose();
if (cmd != null) cmd.Dispose();
When the using block code compiles to intermediate language, it translates the using statements into equivalent try/finally block.

I hope this tip can be useful for all.

  1. No comments yet.
  1. No trackbacks yet.

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: