Posted by: R Manimaran | July 18, 2008

using ‘Using’ statement to free the object resources in C#

When you are using an object that encapsulate any resource, then you have to ensure whether Objects Dispose method is called to clean up the resources.

The same thing can be better done by using the “using” statement in C#.

 

This using statement

  • Simplifies the code
  • Finally clean up the object after the code completion

 

Thus the using statement

·         obtains the resources specified

·         executes the statements

·         finally calls the Dispose method to cleanup the object

 

For ex:

 

using (XmlDocument doc = new XmlDocument())

{

     doc.Load(filename);

     //other operation regarding the xml document

}

Ex.2

using (Myclassmyobj = new Myclass())

 {

   myobj.MyMethod();

 }

Which is similar to

 

Myclassmyobj = new Myclass();

  try

  {

     myobj.MyMethod();

  }

  finally

  {

      if(myobj != null)

      ((IDisposable)myobj).Dispose();

  }

The good usauge of using is in the Database opertaions.

 

DataSetds = new DataSet();
using (SqlConnectionconn = new SqlConnection(this._connectionString))
{
   stringsqlComm = “SET DATEFORMAT DMY “;
   sqlComm += “SELECT * FROM Sample”;
   conn.Open();
   using (SqlCommand comm = new SqlCommand(sqlComm, conn))
   {
      comm.CommandType = CommandType.Text;
      SqlDataAdapterda = new SqlDataAdapter(comm);
      da.Fill(ds, tableName);
  
}
}

or use try/catch/finally

SqlConnectionconn = null;
SqlCommand comm = null;
SqlDataAdapterda = null;
try
{
   conn = new SqlConnection(connectionString);
   sqlComm += “SELECT * FROM Sample”;
   comm = new SqlCommand(sqlComm, conn);
   comm.CommandType = CommandType.Text;
   da = new SqlDataAdapter(comm);
   DataSetds = new DataSet();
   da.Fill(ds, tableName);
}
catch (Exception ex)
{
   // manage exception
}
finally
{
   if(conn != null)
      conn.Dispose();
   if (comm != null)
      comm.Dispose();
   if(da != null)
     
da.Dispose();
}

 

Note:

The using statement is only useful for objects with a lifetime within a method.

The objects you instantiate must implement the System.IDisposable interface

Advertisements

Responses

  1. “The objects you instantiate must implement the System.IDisposable interface”

    .. which is exactly why your first example doesn’t work (XmlDocument).


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

Categories

%d bloggers like this: