|
using - automatic disposal
|
|
|
|
|
Monday, 09 March 2009
|
|
HTML clipboard
SqlConnection connection = null;
try
{
connection = new SqlConnection("connection string");
finally
{
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 ( type variable = initialization ) embeddedStatement
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"))
{
}
|