Information Technology Reference
In-Depth Information
myConnection has already been created, but the code has not entered the
using
block when the SqlCommand constructor executes. Without the
constructor inside the
using
block, the call to Dispose gets skipped. You
must make sure that any objects that implement IDisposable are allocated
inside the scope of a
using
block or a
try
block. Otherwise, resource leaks
can occur.
So far, you've handled the two most obvious cases. Whenever you allocate
one disposable object in a method, the
using
statement is the best way to
ensure that the resources you've allocated are freed in all cases. When you
allocate multiple objects in the same method, create multiple
using
blocks
or write your own single
try
/
finally
block.
There is one more nuance to freeing disposable objects. Some types sup-
port both a Dispose method and a Close method to free resources.
SqlConnection is one of those classes. You could close SqlConnection like
this:
public void
ExecuteCommand(
string
connString,
string
commandString)
{
SqlConnection
myConnection =
null
;
try
{
myConnection =
new
SqlConnection
(connString);
SqlCommand
mySqlCommand =
new
SqlCommand
(commandString, myConnection);
myConnection.Open();
mySqlCommand.ExecuteNonQuery();
}
finally
{
if
(myConnection !=
null
)
myConnection.Close();
}
}
This version does close the connection, but that's not exactly the same as
disposing of it. The Dispose method does more than free resources: It also
notifies the Garbage Collector that the object no longer needs to be final-
ized. Dispose calls GC.SuppressFinalize(). Close typically does not. As a