Using Statement and IDisposable

using statement itself calls the Dispose() method which means to close.It throws exceptions when the network error occurs.
Since the connections are pooled and therefore not immediately destroyed if you are not careful to clean up the resources they reference you will have problems. This is where the using statement comes in.
If the code throws exception without closing the connection then its better to use using.

Code looks like:

using(SqlConnection con=new SqlConnection())
{
//code
}

When a class implements the IDisposable interface it must implement a method called Dispose.This is the method that called when an object goes out of the scope of a using statement.

Code using Dispose() method:

SqlConnection con;
IDisposable con=null;

try
{
//code
}
finally
{
 con.Dispose();
}

This implies that only objects that implement IDisposable can be used in a using statement.
if the object is a class member and therefore can't wrap it's scope in a using statement,then  have your class implement IDisposable and in the Dispose method call the Dispose method of your member object. Then whenever you instantiate your class, do so in a using statement.

For more such information go for Video sessions at Besdotnettraining


Comments