using - automatic disposal PDF Print E-mail
User Rating: / 0
PoorBest 
Monday, 09 March 2009
HTML clipboard

In the Dispose Pattern tutorial, I describe the Dispose Pattern, which shows how to write code that guarantees that the Dispose method will be called on your class.

In the previous tutorial, we had the following code to call dispose, and close our database connection:

SqlConnection connection = null;

try
{
connection = new SqlConnection("connection string");

// Do database accessfinally
{
connection.Dispose();
}
}

The Using statement is designed to simplify this approach, which quickly become complicated when you have more than one resource to dispose of.

The using statement definition, and it's translation are:

// using definitionusing ( type variable = initialization ) embeddedStatement


// ... translates to:if (variable != null)
{
((IDisposable)variable).Dispose();
}
}
}
{ type variable = initialization; try { embeddedStatement } finally {

So, we could re-write our SqlConnection code from above as:

using (SqlConnection connection = new SqlConnection("connection string"))
{
    // Do database access
}

 
< Prev   Next >
School Joomla Templates and Joomla Tutorials