Information Technology Reference
In-Depth Information
That's fine, unless any exceptions get thrown while the SQL command exe-
cutes. In that case, your calls to Dispose() never happen. The
using
state-
ment ensures that Dispose() is called. You allocate an object inside a
using
statement, and the C# compiler generates a
try
/
finally
block around
each object:
public void
ExecuteCommand(
string
connString,
string
commandString)
{
using
(
SqlConnection
myConnection =
new
SqlConnection
(connString))
{
using
(
SqlCommand
mySqlCommand =
new
SqlCommand
(commandString,
myConnection))
{
myConnection.Open();
mySqlCommand.ExecuteNonQuery();
}
}
}
Whenever you use one Disposable object in a function, the
using
clause
is the simplest method to use to ensure that objects get disposed of prop-
erly. The
using
statement generates a
try
/
finally
block around the
object being allocated. These two blocks generate exactly the same IL:
SqlConnection
myConnection =
null
;
// Example Using clause:
using
(myConnection =
new
SqlConnection
(connString))
{
myConnection.Open();
}
// example Try / Catch block:
try
{
myConnection =
new
SqlConnection
(connString);
myConnection.Open();
}