Geeks With Blogs
Carmel's Blog Independent Software Professional

Considure the following code:

public static DataSet GetCity()

{

SqlConnection connection = GetConnection();
SqlDataAdapter adataper = new SqlDataAdapter("select * from City", connection);
DataSet City = new DataSet();
adataper.Fill(City, "City");
return City;

}

This function loads the city table from the database to a dataset, the problem with code is:

1. connection object and adapter object both had a Dispose method but it's not executed,

2. close connection method is not executed.

Why it's good to execute the Dispose method?

The Dispose method usually realese unmanaged resources (resources that Garbage collector doesn't clear without class finilizer),

So why not letting the Garbage Collector to execute the finilizer.

The process in the Garbage Collector that reclaims the resource is more efficient without executing the finalizer,

so the dispose method enables you to do the work in your code.

for that in .NET 2.0 we have the using keyword, declaring an object with the using keyword executes the Dispose method of the object, so its better using.

Lets return to the previous method and rewrite it:

public static DataSet GetCity()

{

DataSet City = new DataSet();
using (SqlConnection connection = GetConnection())

{

using (SqlDataAdapter adataper = new SqlDataAdapter("select * from City", connection))

{

adataper.Fill(City, "City");

connection.Close();

}

}

return City;

}

Posted on Tuesday, November 11, 2008 6:21 AM | Back to top


Comments on this post: using using (free connection)

# re: using using (free connection)
Requesting Gravatar...
You don't actually need to call connection.close on the connection object because it's going to be automatically closed once it leaves the using block. The Dispose() on the connection object actually closes the connection.
Left by Keith Rull on Nov 11, 2008 3:02 PM

Your comment:
 (will show your gravatar)


Copyright © Carmel Halabe | Powered by: GeeksWithBlogs.net