Any time an object you create implements IDisposable
, disposing of it (with or without the using
syntactic sugar) is a good idea.
The benefit of the using
block syntactic sugar (over manual .Dispose()
calls) is that Dispose()
will still be called even if there is an exception and flow leaves the using block.
Also, note that you can stack up the usings, without nested indentation:
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand com = new SqlCommand("",con))
using (SqlDataReader sdr = com.ExecuteReader()) // Still need to open connection ...
{
...
As an aside, a further benefit of using
is that if the IDisposable
variable is declared within the using
, it that the variable is readonly
and cannot be reassigned within the block, e.g.:
using (SqlDataReader sdr = com.ExecuteReader())
{
sdr = new SqlDataReader() // Error